#Entity
#Table(name = "users")
public class User {
private int userId;
private String firstName;
private String middleName;
private String lastName;
private String login;
private String password;
#Transient
private String confirmPassword;
private int sex;
private String email;
private Set<Role> roles;
public User(){}
public String getConfirmPassword() {
return confirmPassword;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "users_roles", joinColumns = {#JoinColumn(name = "user_id")},
inverseJoinColumns = {#JoinColumn(name = "role_id")})
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
#Id
#Column(name = "user_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
#Column(name = "first_name")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "middle_name")
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
#Column(name = "last_name")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name = "login")
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
#Column(name = "password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name = "sex")
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
#Column(name = "email")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "User{" +
"userId=" + userId +
", firstName='" + firstName + '\'' +
", middleName='" + middleName + '\'' +
", lastName='" + lastName + '\'' +
", login='" + login + '\'' +
", password='" + password + '\'' +
", sex=" + sex +
", email=" + email +
'}';
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User)) return false;
User user = (User) o;
if (userId != user.userId) return false;
if (sex != user.sex) return false;
if (!firstName.equals(user.firstName)) return false;
if (middleName != null ? !middleName.equals(user.middleName) : user.middleName != null) return false;
if (!lastName.equals(user.lastName)) return false;
if (login != null ? !login.equals(user.login) : user.login != null) return false;
if (password != null ? !password.equals(user.password) : user.password != null) return false;
if (confirmPassword != null ? !confirmPassword.equals(user.confirmPassword) : user.confirmPassword != null)
return false;
if (!email.equals(user.email)) return false;
return roles != null ? roles.equals(user.roles) : user.roles == null;
}
#Override
public int hashCode() {
int result = userId;
result = 31 * result + firstName.hashCode();
result = 31 * result + (middleName != null ? middleName.hashCode() : 0);
result = 31 * result + lastName.hashCode();
result = 31 * result + (login != null ? login.hashCode() : 0);
result = 31 * result + (password != null ? password.hashCode() : 0);
result = 31 * result + (confirmPassword != null ? confirmPassword.hashCode() : 0);
result = 31 * result + sex;
result = 31 * result + email.hashCode();
result = 31 * result + (roles != null ? roles.hashCode() : 0);
return result;
}
}
#Repository
public class UserDaoImpl implements UserDao {
private static final Logger log = LoggerFactory.getLogger(UserDaoImpl.class);
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void addUser(User user) {
Session session = sessionFactory.getCurrentSession();
session.persist(user);
log.info("User saves successfully. User details: " + user);
}
public void updateUser(User user) {
Session session = sessionFactory.getCurrentSession();
session.update(user);
log.info("User updated successfully. User details: " + user);
}
public void removeUser(int id) {
Session session = sessionFactory.getCurrentSession();
User user = (User) session.load(User.class, id);
if(user != null) {
session.delete(user);
}
log.info("User removed successfully. User details: " + user);
}
public User getUserById(int id) {
Session session = sessionFactory.getCurrentSession();
User user = (User) session.load(User.class, id);
log.info("User loaded successfully. User details: " + user);
return user;
}
#SuppressWarnings("unchecked")
public List<User> listUsers() {
Session session = sessionFactory.getCurrentSession();
List<User> userList = session.createQuery("from users").list();
for (User user : userList) {
log.info("User list: " + user);
}
return userList;
}
}
#Service
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
#Transactional
public void addUser(User user) {
userDao.addUser(user);
}
#Transactional
public void updateUser(User user) {
userDao.updateUser(user);
}
#Transactional
public void removeUser(int id) {
userDao.removeUser(id);
}
#Transactional
public User getUserById(int id) {
return userDao.getUserById(id);
}
#Transactional
public List<User> listUsers() {
return userDao.listUsers();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Notes Web Application</display-name>
<!--Zkoss config-->
<listener>
<listener-class>org.zkoss.zk.ui.http.HttpSessionListener</listener-class>
</listener>
<servlet>
<description>The ZK loader for ZUML pages</description>
<servlet-name>zkLoader</servlet-name>
<servlet-class>org.zkoss.zk.ui.http.DHtmlLayoutServlet</servlet-class>
<init-param>
<param-name>update-uri</param-name>
<param-value>/zkau</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>zkLoader</servlet-name>
<url-pattern>*.zul</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>zkLoader</servlet-name>
<url-pattern>*.zhtml</url-pattern>
</servlet-mapping>
<servlet>
<description>The asynchronous update engine for ZK</description>
<servlet-name>auEngine</servlet-name>
<servlet-class>org.zkoss.zk.au.http.DHtmlUpdateServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>auEngine</servlet-name>
<url-pattern>/zkau/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>60</session-timeout>
</session-config>
<!--Spring config-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>/WEB-INF/pages/index.zul</welcome-file>
</welcome-file-list>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="ru.mightynoobs.springhibernate"/>
<context:component-scan base-package="ru.mightynoobs.springsecurity"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--Database information-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/mightynoobsdb"/>
<property name="username" value="root"/>
<property name="password" value="admin"/>
</bean>
<!--Hibernate 4 SessionFactory Bean definition-->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>ru.mightynoobs.springhibernate.model.user.User</value>
<value>ru.mightynoobs.springhibernate.model.user.Role</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!--UserDao and UserService beans-->
<bean id="userDao" class="ru.mightynoobs.springhibernate.dao.user.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="userService" class="ru.mightynoobs.springhibernate.service.user.UserServiceImpl">
<property name="userDao" ref="userDao"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
<!--Zkoss controller's-->
</beans>
<window id="window" title="User List" border="normal"
apply="ru.mightynoobs.springhibernate.controller.UserNotesListController">
<listbox id="listbox" model="${window$composer.userModel}" checkmark="true" mold="paging" pageSize="9">
<listhead>
<listheader width="32px" />
<listheader label="First Name" align="center" sort="auto(firstName)" />
<listheader label="Middle Name" align="center" sort="auto(middleName)" />
<listheader label="Last Name" align="center" sort="auto(lastName)" />
<listheader label="Sex" align="center" sort="auto(sex)"/>
<listheader label="eMail" align="center" sort="auto(email)" />
</listhead>
<template name="model">
<listitem>
<listcell/>
<listcell label="${each.firstName}"/>
<listcell label="${each.middleName}"/>
<listcell label="${each.lastName}"/>
<listcell label="${each.sex}" style="text-align: right"/>
<listcell label="${each.email}" style="text-align: right"/>
</listitem>
</template>
</listbox>
</window>
and after running tomcat i have this
org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [zkLoader] in context with path [] threw exception
java.lang.NullPointerException
at ru.mightynoobs.springhibernate.service.user.UserServiceImpl.listUsers(UserServiceImpl.java:45)
at ru.mightynoobs.springhibernate.controller.UserNotesListController.<init>(UserNotesListController.java:32)
Sorry for this view of code. Need help with this null pointer. So i have NullPointer. My DB is not empty. Users table has 1 row. It's first time i try integrate zkoss with Spring. Thank you in advance
You should use class name in HQL instead of table name.
Good day, all. I'm newbie in Spring Data + JPA. And i need your help.
It's my first question on stackoverflow, that sorry if i formed my Question not correct.
I start to realise project using Spring Data + JPA + Hibernate, Spring MVC, Use MySQL.
I have DB scheme:
DB of project
DB scheme
application context:
<context:property-placeholder location="classpath:util.properties" />
<!--Activates various annotations to be detected in bean classes: Spring's #Required and #Autowired and so on-->
<context:annotation-config/>
<!-- Datasource. - MySQL -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClass}"/>
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}" />
</bean>
<!--Do not forget activate #Transactional JPA annotation with <annotation-driven/>-->
<!-- JPA Persistence Context and EntityManager configuration -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
<!--packagesToScan - search Entity and mapping them -->
<property name="packagesToScan" value="by.GetItFree" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" >
<property name="generateDdl" value="true" />
<property name="showSql" value="true" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.enable_lazy_load_no_trans">true</prop>
</props>
</property>
</bean>
<!-- Automatic Transaction Participation-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<jpa:repositories base-package="by.GetItFree.orm.repository" entity-manager-factory-ref="entityManagerFactory"
transaction-manager-ref="transactionManager"/>
MVC Config:
<!--
mvc:annotation-driven configures Spring MVC annotations
Support for validating #Controller inputs with #Valid, if a JSR-303 Provider is present on the classpath.
HttpMessageConverter support for #RequestBody method parameters and #ResponseBody method return values
from #RequestMapping or #ExceptionHandler methods.
-->
<mvc:annotation-driven/>
<!-- activate #Transactional JPA annotation -->
<tx:annotation-driven/>
<!-- ViewResolver bean config for mapping strings to jsp views -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- Example: a logical view name of 'showMessage' is mapped to '/WEB-INF/jsp/showMessage.jsp' -->
<property name="order" value="1" />
<property name="prefix" value="/WEB-INF/view" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:view-controller path="/about.html" view-name="/about/about"/>
<mvc:view-controller path="/index.html" view-name="/index"/>
<!-- Static Resources Configuration (get access to static sources such as CSS and JavaScript files) -->
<mvc:resources mapping="/resources/**" location="/resources/" />
Some of JPA Persistence Entites:
Advert:
#Entity
public class Advert {
private int id;
private String karmaReq;
private byte[] image;
private int profileId;
private String profileUsersUsername;
private String head;
private String content;
private byte ordered;
private Timestamp date;
private Profile profile;
private Collection<Comment> commentsById;
#Id
#Column(name = "id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "karmaReq", nullable = true, length = 45)
public String getKarmaReq() {
return karmaReq;
}
public void setKarmaReq(String karmaReq) {
this.karmaReq = karmaReq;
}
#Basic
#Column(name = "image", nullable = false)
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
#Basic
#Column(name = "profile_id", nullable = false)
public int getProfileId() {
return profileId;
}
public void setProfileId(int profileId) {
this.profileId = profileId;
}
#Basic
#Column(name = "profile_users_username", nullable = false, length = 45)
public String getProfileUsersUsername() {
return profileUsersUsername;
}
public void setProfileUsersUsername(String profileUsersUsername) {
this.profileUsersUsername = profileUsersUsername;
}
#Basic
#Column(name = "head", nullable = true, length = 45)
public String getHead() {
return head;
}
public void setHead(String head) {
this.head = head;
}
#Basic
#Column(name = "content", nullable = true, length = 450)
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
#Basic
#Column(name = "ordered", nullable = false)
public byte getOrdered() {
return ordered;
}
public void setOrdered(byte ordered) {
this.ordered = ordered;
}
#Basic
#Column(name = "date", nullable = false)
public Timestamp getDate() {
return date;
}
public void setDate(Timestamp date) {
this.date = date;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Advert advert = (Advert) o;
if (id != advert.id) return false;
if (profileId != advert.profileId) return false;
if (ordered != advert.ordered) return false;
if (karmaReq != null ? !karmaReq.equals(advert.karmaReq) : advert.karmaReq != null) return false;
if (!Arrays.equals(image, advert.image)) return false;
if (profileUsersUsername != null ? !profileUsersUsername.equals(advert.profileUsersUsername) : advert.profileUsersUsername != null)
return false;
if (head != null ? !head.equals(advert.head) : advert.head != null) return false;
if (content != null ? !content.equals(advert.content) : advert.content != null) return false;
if (date != null ? !date.equals(advert.date) : advert.date != null) return false;
return true;
}
#Override
public int hashCode() {
int result = id;
result = 31 * result + (karmaReq != null ? karmaReq.hashCode() : 0);
result = 31 * result + Arrays.hashCode(image);
result = 31 * result + profileId;
result = 31 * result + (profileUsersUsername != null ? profileUsersUsername.hashCode() : 0);
result = 31 * result + (head != null ? head.hashCode() : 0);
result = 31 * result + (content != null ? content.hashCode() : 0);
result = 31 * result + (int) ordered;
result = 31 * result + (date != null ? date.hashCode() : 0);
return result;
}
#ManyToOne
#JoinColumns({#JoinColumn(name = "profile_id", referencedColumnName = "id", nullable = false, insertable = false, updatable = false), #JoinColumn(name = "profile_users_username", referencedColumnName = "users_username", nullable = false, insertable = false, updatable = false)})
public Profile getProfile() {
return profile;
}
public void setProfile(Profile profile) {
this.profile = profile;
}
#OneToMany(mappedBy = "advertByAdvertId")
public Collection<Comment> getCommentsById() {
return commentsById;
}
public void setCommentsById(Collection<Comment> commentsById) {
this.commentsById = commentsById;
}
#Override
public String toString() {
return "Advert{" +
"id=" + id +
", karmaReq='" + karmaReq + '\'' +
", image=" + Arrays.toString(image) +
", profileId=" + profileId +
", profileUsersUsername='" + profileUsersUsername + '\'' +
", head='" + head + '\'' +
", content='" + content + '\'' +
", ordered=" + ordered +
", date=" + date +
", profile=" + profile +
", commentsById=" + commentsById +
'}';
}
}
// I know , that if i comment call profile in to String(), all will be work.
Profile
#Entity
#IdClass(ProfilePK.class)
public class Profile {
private int id;
private String usersUsername;
private Integer karma;
private String phone;
private byte[] icon;
private Collection<Advert> adverts;
private Collection<Comment> comments;
private Collection<Message> messages;
private Users usersByUsersUsername;
#Id
#Column(name = "id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Id
#Column(name = "users_username", nullable = false, length = 45)
public String getUsersUsername() {
return usersUsername;
}
public void setUsersUsername(String usersUsername) {
this.usersUsername = usersUsername;
}
#Basic
#Column(name = "karma", nullable = true)
public Integer getKarma() {
return karma;
}
public void setKarma(Integer karma) {
this.karma = karma;
}
#Basic
#Column(name = "phone", nullable = true, length = 15)
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
#Basic
#Column(name = "icon", nullable = true)
public byte[] getIcon() {
return icon;
}
public void setIcon(byte[] icon) {
this.icon = icon;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Profile profile = (Profile) o;
if (id != profile.id) return false;
if (usersUsername != null ? !usersUsername.equals(profile.usersUsername) : profile.usersUsername != null)
return false;
if (karma != null ? !karma.equals(profile.karma) : profile.karma != null) return false;
if (phone != null ? !phone.equals(profile.phone) : profile.phone != null) return false;
if (!Arrays.equals(icon, profile.icon)) return false;
return true;
}
#Override
public int hashCode() {
int result = id;
result = 31 * result + (usersUsername != null ? usersUsername.hashCode() : 0);
result = 31 * result + (karma != null ? karma.hashCode() : 0);
result = 31 * result + (phone != null ? phone.hashCode() : 0);
result = 31 * result + Arrays.hashCode(icon);
return result;
}
#OneToMany(mappedBy = "profile")
public Collection<Advert> getAdverts() {
return adverts;
}
public void setAdverts(Collection<Advert> adverts) {
this.adverts = adverts;
}
#OneToMany(mappedBy = "profile")
public Collection<Comment> getComments() {
return comments;
}
public void setComments(Collection<Comment> comments) {
this.comments = comments;
}
#OneToMany(mappedBy = "profile")
public Collection<Message> getMessages() {
return messages;
}
public void setMessages(Collection<Message> messages) {
this.messages = messages;
}
#ManyToOne
#JoinColumn(name = "users_username", referencedColumnName = "username", nullable = false, insertable = false, updatable = false)
public Users getUsersByUsersUsername() {
return usersByUsersUsername;
}
public void setUsersByUsersUsername(Users usersByUsersUsername) {
this.usersByUsersUsername = usersByUsersUsername;
}
#Override
public String toString() {
return "Profile{" +
"id=" + id +
", usersUsername='" + usersUsername + '\'' +
", karma=" + karma +
", phone='" + phone + '\'' +
", icon=" + Arrays.toString(icon) +
", adverts=" + adverts +
", comments=" + comments +
", messages=" + messages +
", usersByUsersUsername=" + usersByUsersUsername +
'}';
}
}
ORM
AdvertDAO
/**
* DAO interface responsible for operation with Advertising.
* <p>
* Created by Novik Igor on 09.02.2017.
*/
public interface AdvertDAO {
/**
* Method returned list of Advert's from the DB.
*
* #return list of Advertising's.
*/
List<Advert> findAll();
/**
* Method returned list of Advert from the DB according ID.
*
* #param head id of the Advert;
* #return Advertising according id.
*/
Advert findByHead(String head);
}
AdvertDAORepository
/**
* SpringData AdvertDAO repository.
*
* Created by Novik Igor on 10.02.2017.
*/
public interface AdvertDAORepository extends CrudRepository<Advert,Integer> {
List<Advert> findByHead(String head);
}
Service for Spring Data/JPA - AdvertDAOImpl
/**
* Repository bean that implements JPA DAO Advert interfaces responsible for operation with Advertising from DB.
* <p>
* Created by nolik on 10.02.17.
*/
#Service("jpaAdvertDAO")
#Repository
#Transactional
public class AdvertDAOImpl implements AdvertDAO {
#Autowired
private AdvertDAORepository advertDAORepository;
#Override
public List<Advert> findAll() {
return Lists.newArrayList(advertDAORepository.findAll());
}
#Override
public Advert findByHead(String head) {
return (Advert) advertDAORepository.findByHead(head);
}
}
Test MVC Controller:
#Controller
public class TestController {
#Autowired
AdvertDAO jpaAdvertDAO;
#Autowired
CommentDAO jpaCommentDAO;
#RequestMapping(value = "/testCall", method = RequestMethod.GET)
public ModelAndView readCookieExample() {
System.out.println(" Test console");
return new ModelAndView("/error/errorpage");
}
#RequestMapping(value = "/jpaFindAllAdvert", method = RequestMethod.GET)
public ModelAndView jpaFindAllAdvert() {
System.out.println("ORMController ormFindAllUsers is called");
List<Advert> adverts = jpaAdvertDAO.findAll();
return new ModelAndView("/error/test", "resultObject", adverts);
}
#RequestMapping(value = "/jpaFindAllComments", method = RequestMethod.GET)
public ModelAndView jpaFindAllComments() {
System.out.println("ORMController FindAllComments is called");
List<Comment> comments = jpaCommentDAO.findAll();
return new ModelAndView("/error/test", "resultObject", comments);
}
}
Simple JSP for showing result of calling "/jpaFindAllAdvert"
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Test</title>
</head>
<body>
<%--Find All Adverts--%>
${resultObject}
</body>
</html>
Firstly i faced with the next exception:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: by.GetItFree.entities.Profile.adverts, could not initialize proxy - no Session
org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:563)
org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:205)
org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:542)
org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:133)
org.hibernate.collection.internal.PersistentBag.toString(PersistentBag.java:509)
java.lang.String.valueOf(String.java:2994)
java.lang.StringBuilder.append(StringBuilder.java:131)
by.GetItFree.entities.Profile.toString(Profile.java:144)
java.lang.String.valueOf(String.java:2994)
java.lang.StringBuilder.append(StringBuilder.java:131)
by.GetItFree.entities.Advert.toString(Advert.java:174)
java.lang.String.valueOf(String.java:2994)
java.lang.StringBuilder.append(StringBuilder.java:131)
java.util.AbstractCollection.toString(AbstractCollection.java:462)
org.apache.el.lang.ELSupport.coerceToString(ELSupport.java:497)
org.apache.el.lang.ELSupport.coerceToType(ELSupport.java:529)
org.apache.el.ExpressionFactoryImpl.coerceToType(ExpressionFactoryImpl.java:47)
javax.el.ELContext.convertToType(ELContext.java:304)
org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:186)
org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:944)
org.apache.jsp.WEB_002dINF.view.error.test_jsp._jspService(test_jsp.java:118)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:443)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:168)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:303)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1271)
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1037)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:980)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
I google that it's a result of N+1 SQL problem for Hibernate for Leazy initialisation of Joined with #ManyToONe relations.
I use way to fix with adding:
<prop key="hibernate.enable_lazy_load_no_trans">true</prop>
to "Jpa Properties"
After this i faced with: StackOverflow exeption:
java.lang.StackOverflowError
java.util.AbstractCollection.toString(AbstractCollection.java:454)
org.hibernate.collection.internal.PersistentBag.toString(PersistentBag.java:510)
java.lang.String.valueOf(String.java:2994)
java.lang.StringBuilder.append(StringBuilder.java:131)
by.GetItFree.entities.Profile.toString(Profile.java:144)
java.lang.String.valueOf(String.java:2994)
java.lang.StringBuilder.append(StringBuilder.java:131)
by.GetItFree.entities.Advert.toString(Advert.java:174)
java.lang.String.valueOf(String.java:2994)
java.lang.StringBuilder.append(StringBuilder.java:131)
java.util.AbstractCollection.toString(AbstractCollection.java:462)
org.hibernate.collection.internal.PersistentBag.toString(PersistentBag.java:510)
java.lang.String.valueOf(String.java:2994)
java.lang.StringBuilder.append(StringBuilder.java:131)
by.GetItFree.entities.Profile.toString(Profile.java:144)
java.lang.String.valueOf(String.java:2994)
java.lang.StringBuilder.append(StringBuilder.java:131)
by.GetItFree.entities.Advert.toString(Advert.java:174)
Etc.. - very long listing
In Tocat Log in the last case - i see big listing JPQL/or HSQL i'm not shure:
RMController ormFindAllUsers is called
Hibernate: select advert0_.id as id1_1_, advert0_.content as content2_1_, advert0_.date as date3_1_, advert0_.head as head4_1_, advert0_.image as image5_1_, advert0_.karmaReq as karmaReq6_1_, advert0_.ordered as ordered7_1_, advert0_.profile_users_username as profile_9_1_, advert0_.profile_id as profile_8_1_ from Advert advert0_
Hibernate: select profile0_.users_username as users_us1_5_0_, profile0_.id as id2_5_0_, profile0_.icon as icon3_5_0_, profile0_.karma as karma4_5_0_, profile0_.phone as phone5_5_0_, users1_.username as username1_6_1_, users1_.enabled as enabled2_6_1_, users1_.password as password3_6_1_ from Profile profile0_ inner join Users users1_ on profile0_.users_username=users1_.username where profile0_.users_username=? and profile0_.id=?
Hibernate: select adverts0_.profile_users_username as profile_9_1_0_, adverts0_.profile_id as profile_8_1_0_, adverts0_.id as id1_1_0_, adverts0_.id as id1_1_1_, adverts0_.content as content2_1_1_, adverts0_.date as date3_1_1_, adverts0_.head as head4_1_1_, adverts0_.image as image5_1_1_, adverts0_.karmaReq as karmaReq6_1_1_, adverts0_.ordered as ordered7_1_1_, adverts0_.profile_users_username as profile_9_1_1_, adverts0_.profile_id as profile_8_1_1_ from Advert adverts0_ where adverts0_.profile_users_username=? and adverts0_.profile_id=?
Hibernate: select profile0_.users_username as users_us1_5_0_, profile0_.id as id2_5_0_, profile0_.icon as icon3_5_0_, profile0_.karma as karma4_5_0_, profile0_.phone as phone5_5_0_, users1_.username as username1_6_1_, users1_.enabled as enabled2_6_1_, users1_.password as password3_6_1_ from Profile profile0_ inner join Users users1_ on profile0_.users_username=users1_.username where profile0_.users_username=? and profile0_.id=?
My progect on github: ProgectSourceCode
What's the reason of this behaiviour. And what's the solution?
Thx for your attention and support.
The reason you're having this problem is because associations that your view requires should be initialized inside a transaction boundary to avoid the LazyInitializationException. Adding an option to load collections outside of a transaction is merely a bandaid and doesn't truly address the underlying design flaw of your code.
If your view requires that you load Profile and its associated collection of Advert entities, then your either your data access should should specifically toggle that behavior or the query specify that you need that collection initialized.
There are a number of ways you can trigger this collection to be loaded as part of a query.
JPQL/HQL using a JOIN FETCH on the adverts collection.
Specify a join fetch using the Criteria API
Use #FetchProfile to toggle a specific fetch strategy by name.
Use #NamedEntityGraph.
I have a OneToMany data model with two entities. One machine contains many characteristics.
Problem: I am trying to create entities without a cyclic dependency.
But I get the issue:
Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/spring-config.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:747)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4842)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5303)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:1225)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.access$600(EntityManagerFactoryBuilderImpl.java:119)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:853)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:843)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:398)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:842)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
... 21 more
Caused by: org.hibernate.MappingException: Could not determine type for: java.util.Set, at table: machine, for columns: [org.hibernate.mapping.Column(characteristics)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:336)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:310)
at org.hibernate.mapping.Property.isValid(Property.java:241)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:496)
at org.hibernate.mapping.RootClass.validate(RootClass.java:270)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1358)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1849)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
... 29 more
My database:
machine:
create statement:
CREATE TABLE `machine` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`description` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8
entity:
#Entity
#Table(name = "machine")
public class Machine {
private int machine_id;
private String name;
private String description;
private Set<Characteristic> characteristics;
public Set<Characteristic> getCharacteristics() {
return characteristics;
}
public void setCharacteristics(Set<Characteristic> characteristics){
this.characteristics = characteristics;
}
public Machine(){}
public Machine(String name, String description){
this.name = name;
this.description = description;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="id")
public int getId() {
return machine_id;
}
public void setId(int machine_id) {
this.machine_id = machine_id;
}
#Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name="description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Characteristic
create statement:
CREATE TABLE `characteristic` (
`characteristic_id` int(11) NOT NULL AUTO_INCREMENT,
`machine_id` int(11) NOT NULL DEFAULT '0',
`name` varchar(45) DEFAULT NULL,
`description` varchar(45) DEFAULT NULL,
`type` int(11) NOT NULL,
`value` int(11) DEFAULT NULL,
PRIMARY KEY (`characteristic_id`),
) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=latin1
entity:
#Entity
#Table(name = "characteristic")
public class Characteristic {
private int characteristic_id;
private String name;
private String description;
private int type;
private int value;
public Characteristic() {}
public Characteristic(String description, int type, int value) {
this.description = description;
this.type = type;
this.value = value;
}
public Characteristic(int characteristic_id, String description, int type, int value) {
this.characteristic_id = characteristic_id;
this.description = description;
this.type = type;
this.value = value;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="characteristic_id")
public int getCharacteristic_Id() {
return characteristic_id;
}
public void setCharacteristic_Id(int characteristic_id) {
this.characteristic_id = characteristic_id;
}
#Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name="description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name="type")
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
#Column(name="value")
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
Spring-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.mego.smscloud" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/maschinedb?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</bean>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="database" value="MYSQL"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
<property name="packagesToScan" value="com.mego.smscloud.entity"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"/>
<jpa:repositories base-package="com.mego.smscloud.repository" />
</beans>
it's simply a problem with the mapping between Characteristic and Machine.
The log tells that Hibernate doesn't know which type to use for mapping.
You should add a #OneToMany annotation on method getCharacteristics() in class Machine.
You could have a look here for collection mapping at the section OneToMany Unidirectional (with or without jointable):
https://docs.jboss.org/hibernate/annotations/3.4/reference/en/html_single/#entity-mapping-association-collections
#Entity
#Table(name = "machine")
public class Machine {
private int machine_id;
private String name;
private String description;
private Set<Characteristic> characteristics;
#OneToMany
#JoinColumn(name="machine_id")
public Set<Characteristic> getCharacteristics() {
return characteristics;
}
public void setCharacteristics(Set<Characteristic> characteristics){
this.characteristics = characteristics;
}
public Machine(){}
public Machine(String name, String description){
this.name = name;
this.description = description;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="id")
public int getId() {
return machine_id;
}
public void setId(int machine_id) {
this.machine_id = machine_id;
}
#Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name="description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Hope this help
I'm developing a little web app for an exam purpose, but I'm encountering several problems with the Dao methods, they all return a NullPointerException.
This is the Façade:
#Stateless(name = "administratorFacade")
public class AdministratorFacade {
#PersistenceContext(unitName = "clinic-unit")
private EntityManager em;
public Administrator getAdministrator(String username){
AdministratorDaoJPA administratorDao = new AdministratorDaoJPA();
Administrator administrator = administratorDao.findByUsername(username);
return administrator;
} //An example of method that uses DAO
This is the DAO:
public class AdministratorDaoJPA implements AdministratorDao {
#PersistenceContext(unitName = "clinic-unit", type = PersistenceContextType.EXTENDED)
private EntityManager em;
#Override
public Administrator findByUsername(String username){
Query query = em.createQuery("SELECT a FROM Administrator a WHERE a.username=?");
return (Administrator)query.setParameter(1,username).getSingleResult();
}
And there is Administrator.java:
#Entity
#NamedQuery(name="allAdministrators", query="SELECT a FROM Administrator a")
public class Administrator {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(unique = true, nullable = false)
private String username;
#Column(nullable = false)
private String name;
#Column(nullable = false)
private String surname;
#Column(nullable = false)
private String pwd;
public Administrator(){}
public Administrator(String username, String name, String surname, String pwd) {
this.username=username;
this.name = name;
this.surname=surname;
this.pwd = pwd;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username ;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return this.pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getSurname() {
return surname;
}
public void setSurname(String surName) {
this.surname = surName;
}
#Override
public boolean equals(Object o) {
Administrator adm = (Administrator) o;
return adm.getUsername().equals(this.getUsername());
}
#Override
public int hashCode() {
return this.getUsername().hashCode();
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Adinistrator");
sb.append("{id='").append(id);
sb.append(", name='").append(name);
sb.append(", surname='").append(surname);
sb.append(", username='").append(username);
sb.append("}\n");
return sb.toString();
}
}
And finally the persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="clinic-unit" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>PostgreSQL Database</jta-data-source>
<class>it.clinic.model.Indicator</class>
<class>it.clinic.model.Administrator</class>
<class>it.clinic.model.Exam</class>
<class>it.clinic.model.ExamTypology</class>
<class>it.clinic.model.Medic</class>
<class>it.clinic.model.Patient</class>
<class>it.clinic.model.Prerequisite</class>
<properties>
<!-- ad ogni esecuzione viene creato lo schema, cancellando il contenuto delle tabelle
<property name="hibernate.hbm2ddl.auto" value="create"/> -->
<!-- SQL dialect -->
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<!--- Per avere info sulle istruzioni SQL inviate al db -->
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.archive.autodetection" value="class"/>
</properties>
</persistence-unit>
</persistence>
Stacktrace:
java.lang.NullPointerException
it.clinic.persistence.ExamTypologyDaoJPA.findAll(ExamTypologyDaoJPA.java:54)
it.clinic.facade.AdministratorFacade.getAllExamTypologies(AdministratorFacade.java:53)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:205)
org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:186)
org.apache.openejb.monitoring.StatsInterceptor.record(StatsInterceptor.java:181)
org.apache.openejb.monitoring.StatsInterceptor.invoke(StatsInterceptor.java:100)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:205)
org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:186)
org.apache.openejb.core.interceptor.InterceptorStack.invoke(InterceptorStack.java:85)
org.apache.openejb.core.stateless.StatelessContainer._invoke(StatelessContainer.java:236)
org.apache.openejb.core.stateless.StatelessContainer.invoke(StatelessContainer.java:203)
org.apache.openejb.core.ivm.EjbObjectProxyHandler.synchronizedBusinessMethod(EjbObjectProxyHandler.java:265)
org.apache.openejb.core.ivm.EjbObjectProxyHandler.businessMethod(EjbObjectProxyHandler.java:260)
org.apache.openejb.core.ivm.EjbObjectProxyHandler._invoke(EjbObjectProxyHandler.java:89)
org.apache.openejb.core.ivm.BaseEjbProxyHandler.invoke(BaseEjbProxyHandler.java:347)
it.clinic.facade.AdministratorFacade$$LocalBeanProxy.getAllExamTypologies(it/clinic/facade/AdministratorFacade.java)
it.clinic.controller.ExamTypologyController.examTypologiesList(ExamTypologyController.java:35)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.apache.tomee.catalina.JavaeeInstanceManager.postConstruct(JavaeeInstanceManager.java:163)
org.apache.tomee.mojarra.TomEEInjectionProvider.invokePostConstruct(TomEEInjectionProvider.java:57)
com.sun.faces.mgbean.BeanBuilder.invokePostConstruct(BeanBuilder.java:221)
com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:103)
com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:257)
com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:117)
com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
com.sun.faces.el.ChainTypeCompositeELResolver.getValue(ChainTypeCompositeELResolver.java:90)
org.apache.jasper.el.JasperELResolver.getValue(JasperELResolver.java:96)
org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:80)
org.apache.el.parser.AstValue.getValue(AstValue.java:137)
org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
org.apache.jasper.el.JspValueExpression.getValue(JspValueExpression.java:115)
org.apache.taglibs.standard.tag.common.core.ForEachSupport.prepare(ForEachSupport.java:151)
javax.servlet.jsp.jstl.core.LoopTagSupport.doStartTag(LoopTagSupport.java:256)
org.apache.jsp.ExamTypologies_jsp._jspx_meth_c_005fforEach_005f0(ExamTypologies_jsp.java:280)
org.apache.jsp.ExamTypologies_jsp._jspService(ExamTypologies_jsp.java:232)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
com.sun.faces.context.ExternalContextImpl.dispatch(ExternalContextImpl.java:642)
com.sun.faces.application.view.JspViewHandlingStrategy.executePageToBuildView(JspViewHandlingStrategy.java:363)
com.sun.faces.application.view.JspViewHandlingStrategy.buildView(JspViewHandlingStrategy.java:153)
com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:99)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.apache.openejb.server.httpd.WebBeansFilter.doFilter(WebBeansFilter.java:52)
I'm using JPA with Tomee and JSF 2.2.
I hope you will help me to go through this :)
You're using
new AdministratorDaoJPA()
to get your DAO. So the container can't inject anything into that object, and the entityManager field thus has its default value: null.
For injection to happen, you must let the container create and inject the objects.
You also don't need the entity manager in your facade, so there is no point in injecting it there. What you need to inject is the DAO:
#Inject
private AdministratorDaoJPA administratorDao;
I am getting following exception at query.can you please tell mw whats wrong is in my code?
org.hibernate.MappingException: No Dialect mapping for JDBC type: -1
at org.hibernate.dialect.TypeNames.get(TypeNames.java:79)
at org.hibernate.dialect.TypeNames.get(TypeNames.java:104)
at org.hibernate.dialect.Dialect.getHibernateTypeName(Dialect.java:393)
at org.hibernate.loader.custom.CustomLoader$Metadata.getHibernateType(CustomLoader.java:582
at org.hibernate.loader.custom.CustomLoader$ScalarResultColumnProcessor.performDiscovery(Custom Loader.java:508)
at org.hibernate.loader.custom.CustomLoader.autoDiscoverTypes(CustomLoader.java:524)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1821)
at org.hibernate.loader.Loader.doQuery(Loader.java:697)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
at org.hibernate.loader.Loader.doList(Loader.java:2232)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2129)
at org.hibernate.loader.Loader.list(Loader.java:2124)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:312)
at org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1723)
at org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:165)
at org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:175)
at com.bdisys.promorphics.dao.impl.BlogDaoImpl.getTopBlogsQuesByDate(BlogDaoImpl.java:126)
at org.apache.jsp.Mydetails_jsp._jspService(Mydetails_jsp.java:935)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:176)
at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145)
at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92)
at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:381)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
at java.lang.Thread.run(Unknown Source)
Blog.java :
#SuppressWarnings("serial")
#Entity
#Table(name="blog")
public class Blog extends BaseDomain {
#Column(name="blog_title")
private String blogTitle;
#Column(name="blog_text",columnDefinition="TEXT")
private String blogText;
#Enumerated(EnumType.STRING)
#Column(name="blog_status")
private Status blogStatus;
#OneToOne
#JoinColumn(name="created_by", nullable=false)
private User createdBy;
#OneToOne
#JoinColumn(name="blog_category", nullable=false)
private BlogCategory blogCategory;
#Temporal(TemporalType.DATE)
#Column(name="created_date")
private Date createdDate;
#Column(name="likes")
private Long likes;
#Column(name="uploads")
private String uploads;
#Column(name="youtube_link")
private String youTubeLik;
#Column(name="moderator_comment")
private String moderatorComment;
#Lob
#Column(name="blog_description")
private String blog_desc;
#ManyToOne
#JoinColumn(name="users")
private User users;
public User getUsers() {
return users;
}
public void setUsers(User users) {
this.users = users;
}
public String getBlog_desc() {
return blog_desc;
}
public void setBlog_desc(String blog_desc) {
this.blog_desc = blog_desc;
}
public String getBlogTitle() {
return blogTitle;
}
public void setBlogTitle(String blogTitle) {
this.blogTitle = blogTitle;
}
public String getBlogText() {
return blogText;
}
public void setBlogText(String blogText) {
this.blogText = blogText;
}
public Status getBlogStatus() {
return blogStatus;
}
public void setBlogStatus(Status blogStatus) {
this.blogStatus = blogStatus;
}
public User getCreatedBy() {
return createdBy;
}
public void setCreatedBy(User createdBy) {
this.createdBy = createdBy;
}
public BlogCategory getBlogCategory() {
return blogCategory;
}
public void setBlogCategory(BlogCategory blogCategory) {
this.blogCategory = blogCategory;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public Long getLikes() {
return likes;
}
public void setLikes(Long likes) {
this.likes = likes;
}
public String getUploads() {
return uploads;
}
public void setUploads(String uploads) {
this.uploads = uploads;
}
public String getYouTubeLik() {
return youTubeLik;
}
public void setYouTubeLik(String youTubeLik) {
this.youTubeLik = youTubeLik;
}
public String getModeratorComment() {
return moderatorComment;
}
public void setModeratorComment(String moderatorComment) {
this.moderatorComment = moderatorComment;
}
}
Askquestions.java :
#SuppressWarnings("serial")
#Entity
#Table(name="askquestions")
public class Askquestions extends BaseDomain {
#Column(length = 100, name = "id_subscribers")
private String idSubscribers;
#Column(length = 100, name = "is_anonymous")
private String isAnonymous;
#Column(length = 100, name = "display_name")
private String displayName;
#Temporal(TemporalType.DATE)
#Column(length = 100, name = "created_on")
private Date createdQuesOn;
#Lob
#Column(name = "ask_question")
private String askQuestion;
#Column(length = 100, name = "ask_to_whom")
private String askToWhom;
#Lob
#Column(name="question_of_day")
private String questionOfDay;
#ManyToOne
#JoinColumn(name="ask_category")
private Askcategory askcategory;
#ManyToOne
#JoinColumn(name="users")
private User users;
public User getUsers() {
return users;
}
public void setUsers(User users) {
this.users = users;
}
public Askcategory getAskcategory() {
return askcategory;
}
public void setAskcategory(Askcategory askcategory) {
this.askcategory = askcategory;
}
public String getQuestionOfDay() {
return questionOfDay;
}
public void setQuestionOfDay(String questionOfDay) {
this.questionOfDay = questionOfDay;
}
public String getIdSubscribers() {
return idSubscribers;
}
public void setIdSubscribers(String idSubscribers) {
this.idSubscribers = idSubscribers;
}
public String getIsAnonymous() {
return isAnonymous;
}
public void setIsAnonymous(String isAnonymous) {
this.isAnonymous = isAnonymous;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getAskQuestion() {
return askQuestion;
}
public void setAskQuestion(String askQuestion) {
this.askQuestion = askQuestion;
}
public String getAskToWhom() {
return askToWhom;
}
public void setAskToWhom(String askToWhom) {
this.askToWhom = askToWhom;
}
public Date getCreatedQuesOn() {
return createdQuesOn;
}
public void setCreatedQuesOn(Date createdQuesOn) {
this.createdQuesOn = createdQuesOn;
}
}
BlogDaoimpl Method:this query is not getting executed while other small queries are getting executed.why is it happening????
String sql = " select title , date from (select blog_title as title ,created_date as date from blog union select ask_question as title , created_on as date from askquestions ) as aa order by date desc";
SQLQuery query = getSession().createSQLQuery(sql);
return query.list();
hibrnate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- <property name="hibernate.connection.password">websitebdi</property>
<property name="hibernate.connection.url">jdbc:mysql://184.172.182.251:3306/bdiwebsite</property>
<property name="hibernate.connection.username">bdiwebsite</property> -->
<property name="hibernate.connection.password">MAYbdiSYS2008</property>
<property name="hibernate.connection.url">jdbc:mysql://115.119.114.10:3306/bdisystems</property>
<property name="hibernate.connection.username">admin</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">false</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
<property name="hibernate.connection.provider_class">
org.hibernate.connection.C3P0ConnectionProvider
</property>
<!-- The maximum number of connections -->
<property name="hibernate.c3p0.max_size">20</property>
<!-- The minimum number of connections -->
<property name="hibernate.c3p0.min_size">5</property>
<!-- Get a connection timeout , If you exceed this time , Throws an exception, in milliseconds -->
<property name="hibernate.c3p0.timeout">120</property>
<!-- The maximum number of PreparedStatement -->
<property name="hibernate.c3p0.max_statements">100</property>
<!-- Every 120 seconds checking connection idle connection in the pool, the unit is in seconds -->
<property name="hibernate.c3p0.idle_test_period">120</property>
<!-- When connection pooling connections inside out, look at the new C3P0 get the number of connections -->
<property name="hibernate.c3p0.acquire_increment">2</property>
<!-- Always verify the connection -->
<property name="hibernate.c3p0.validate">true</property>
<!--
<property name="hibernate.c3p0.max_size">100</property>
<property name="hibernate.c3p0.min_size">0</property>
<property name="hibernate.c3p0.acquire_increment">1</property>
<property name="hibernate.c3p0.idle_test_period">300</property>
<property name="hibernate.c3p0.max_statements">0</property>
<property name="hibernate.c3p0.timeout">100</property>
-->
<!-- Mapping Classes -->
<mapping class="com.bdisys.promorphics.domain.BlogCategory"/>
<mapping class="com.bdisys.promorphics.domain.Blog"/>
<mapping class="com.bdisys.promorphics.domain.Career"/>
<mapping class="com.bdisys.promorphics.domain.Partners"/>
<mapping class="com.bdisys.promorphics.domain.Askcategory"/>
<mapping class="com.bdisys.promorphics.domain.Askquestions"/>
<mapping class="com.bdisys.promorphics.domain.Askanswers"/>
</session-factory>
</hibernate-configuration>
Create a custom Dialect (extending MySQLDialect) and in your constructor add
registerHibernateType(Types.LONGVARCHAR, TextType.INSTANCE.getName());
public class MySQLDialect extends MySQLDialect {
public AGOSQLServerDialect() {
super();
registerHibernateType(Types.LONGVARCHAR, TextType.INSTANCE.getName());
}
}
Remember to change dialect class into Hibernate config file
<property name="hibernate.dialect">path.to.YourDialect</property>