when i use hibernate to save entity i found that session can't save it in Transaction. i must flush and clear session.but i have not to do like this before in other projects,is there anything wrong with the transaction configs in my xml files?Any answers are appreciated : )
hibernate.cfg.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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:property-placeholder location="classpath:application.properties"/>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driverClassName}"></property>
<property name="url" value="${url}"></property>
<property name="username" value="${db.userName}"></property>
<property name="password" value="${db.password}"></property>
</bean>
<bean id="sessionFactory" name="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<!--<prop key="current_session_context_class">thread</prop>-->
</props>
</property>
<property name="packagesToScan" value="com.gtis"/>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--<bean id="transactionProxy"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
abstract="true">
<property name="transactionManager" ref="transactionManager"></property>
<property name="transactionAttributes">
<props>
<prop key="save*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="modify*">PROPAGATION_REQUIRED,-myException</prop>
<prop key="del*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>-->
<!--<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="create*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="import*" propagation="REQUIRED" />
<tx:method name="*" propagation="NOT_SUPPORTED" read-only="true" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="serviceOperation" expression="execution(* com.gtis.service.*Service.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />
</aop:config>-->
</beans>
Dao
package com.gtis.dao;
import com.gtis.model.Student;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.util.List;
/**
* Created by u on 2016/3/15.
*/
#Repository
public class StudentDao {
#Resource
private SessionFactory sessionFactory;
private Session getSession(){
return sessionFactory.getCurrentSession();
}
public Student query(String id) throws Exception{
if(StringUtils.isBlank(id)){
return (Student)getSession().get(Student.class,id);
}else{
throw new Exception("id is required");
}
}
public List<Student> queryAll(){
String hql = "from com.gtis.model.Student";
Query query = getSession().createQuery(hql);
return query.list();
}
public void save(Student student)throws Exception{
if(student!=null){
System.out.println("sessionFactory="+sessionFactory);
System.out.println("session="+getSession());
// Session session = getSession();
getSession().save(student);
// session.flush();
// session.clear();
// session.close();
}else{
throw new Exception("object is required");
}
}
public void delete(Student student)throws Exception{
if(student!=null){
getSession().delete(student);
}else{
throw new Exception("object is required");
}
}
}
Service
package com.gtis.service;
import com.gtis.dao.StudentDao;
import com.gtis.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by u on 2016/3/15.
*/
#Service
public class StudentService {
#Autowired
StudentDao studentDao;
public Student getStudent(String id) throws Exception {
return studentDao.query(id);
}
public List<Student> getAll() throws Exception{
return studentDao.queryAll();
}
#Transactional
public void save(Student student)throws Exception{
studentDao.save(student);
}
#Transactional
public void delete(Student student) throws Exception{
studentDao.delete(student);
}
}
> Controller
package com.gtis.controller;
import com.gtis.model.Student;
import com.gtis.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Created by u on 2016/3/15.
*/
#Controller
public class StudentController {
#Autowired
StudentService studentService;
#RequestMapping("get")
public String get(){
Student student = new Student();
student.setName("avc");
try {
studentService.save(student);
} catch (Exception e) {
e.printStackTrace();
}
return "somwhere";
}
}
Your DAO should implement an interface and inject that interface via Autowired to your Service which uses the #Transactional annotation in order to work.
So:
#Repository
public class StudentDao implements StudentDaoInterface {
//your rest code here
}
And:
#Service
public class StudentService {
#Autowired
StudentDaoInterface studentDao;
public Student getStudent(String id) throws Exception {
return studentDao.query(id);
}
public List<Student> getAll() throws Exception{
return studentDao.queryAll();
}
#Transactional
public void save(Student student)throws Exception{
studentDao.save(student);
}
#Transactional
public void delete(Student student) throws Exception{
studentDao.delete(student);
}
}
And of course dont forget to declare your public methods of your DAO to the interface.
Oh and do the same for your Service class (interface, autowire the interface instead of the class etc).
You should Autowired the sessionfactory to give spring a full control to commit your transactions.
Related
I'm unit testing my Hibernate DAO layer with jUnit4 and Mockito and I'm having problems mocking get(Class<T> entityType, Serializable id).
I have no errors along the way, the only thing is that my assertion fails as actualAddress is null.
// imports here
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "classpath:applicationContext.xml")
public class AddressDAOImplTest {
#Autowired
#InjectMocks
private AddressDAO addressDAO;
#Mock
private SessionFactory sessionFactory;
#Mock
private Session session;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
#Test
public void getAddress() {
Address expectedAddress = getTestAddress(1);
Mockito
.doReturn(session)
.when(sessionFactory)
.openSession();
Mockito
.doReturn(expectedAddress)
.when(session)
.get(Matchers.eq(Address.class), Matchers.anyInt()); // doesn't match
Mockito
.doNothing()
.when(session)
.close();
Address actualAddress = addressDAO.getAddress(1);
Assert.assertEquals(expectedAddress, actualAddress);
}
}
somewhere AddressDAOImpl:
public Address getAddress(Integer id) {
Session session = sessionFactory.openSession();
Address address = null;
try {
address = session.get(Address.class, id); // returns null as it can't match the mocked method
} catch (Exception e) {
// some logging here :)
} finally {
session.close();
return address;
}
}
SessionFactory setup:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.webservices.models"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
<bean id="dataSource"
class="org.apache.tomcat.dbcp.dbcp2.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
Hibernate props:
jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:orders;DB_CLOSE_DELAY=-1
jdbc.username=
jdbc.password=
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.hbm2ddl.auto=create-drop
hibernate.show_sql=true
To my understanding get(Matchers.eq(Address.class), Matchers.anyInt()) doesn't match the actual method, which leads to null as a return value.
I'd greatly appreciate your help!
I'm having problem with my web-app, cannot deploy the project to WildFly.
Problem:
Caused by: java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bookedRoomDao': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined
at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:222)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:87)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.start(UndertowDeploymentService.java:72)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1948) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1881) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
... 3 more
Here is my application-context.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>text_resources</value>
</list>
</property>
</bean>
<bean name="exceptionResolver" class="com.booking.common.HotelException" autowire="byName">
<property name="exceptionMappings">
<props>
<prop key="javax.servlet.jsp.JspException">exception</prop>
<prop key="javax.servlet.ServletException">exception</prop>
<prop key="java.lang.Exception">exception</prop>
<prop key="java.lang.Throwable">exception</prop>
<prop key="java.lang.RuntimeException">exception</prop>
<prop key="org.springframework.web.bind.ServletRequestBindingException">exception</prop>
</props>
</property>
</bean>
<bean id="mailSession" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:jboss/mail/Default"/>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/booking-war"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" lazy-init="true" autowire="default">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.booking.member.vo" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
<context:component-scan base-package="com.booking.dao" />
<context:component-scan base-package="com.booking.member" />
<context:component-scan base-package="com.booking.service" />
</beans>
UserDaoImpl.java
package com.booking.dao.impl;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.booking.dao.GenericDao;
import com.booking.dao.UserDao;
import com.booking.member.vo.AuthenticateUser;
#Repository("userDao")
public class UserDaoImpl implements UserDao{
#Autowired
GenericDao<AuthenticateUser,Long> genericDao;
#PersistenceContext
EntityManager entityManager;
#Override
public List<AuthenticateUser> userByName(String username) {
String queryStr = "SELECT u FROM AuthenticateUser u WHERE u.username= ? ";
return entityManager.createQuery(queryStr)
.setParameter(1,username).getResultList();
}
public AuthenticateUser create(AuthenticateUser t) {
return genericDao.create(t);
}
public AuthenticateUser read(Long id, Class<AuthenticateUser> c) {
return genericDao.read(id, c);
}
public AuthenticateUser update(AuthenticateUser t) {
return genericDao.update(t);
}
public void delete(AuthenticateUser t) {
genericDao.delete(t);
}
public List<AuthenticateUser> getAll(Class<AuthenticateUser> c) {
return genericDao.getAll(c);
}
}
GenericDaoImpl.java :
package com.booking.dao.impl;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.ejb.HibernateEntityManager;
import org.springframework.stereotype.Repository;
import com.booking.dao.GenericDao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
#Repository("genericDao")
public class GenericDaoImpl<T,PK extends Serializable> implements GenericDao<T, PK> {
protected Class<T> entityClass;
#PersistenceContext
protected EntityManager entityManager;
#Override
public T create(T t) {
this.entityManager.persist(t);
return t;
}
#Override
public T read(PK id,Class<T> c) {
return (T)this.entityManager.find(c, id);
}
#Override
public T update(T t) {
return this.entityManager.merge(t);
}
#Override
public void delete(T t) {
t = this.entityManager.merge(t);
this.entityManager.remove(t);
}
#Override
public List<T> getAll(Class<T> c){
return this.entityManager.createQuery("SELECT o FROM "+ c.getName() +" o").getResultList();
}
#Override
public List<T> getByFilter(T filter){
Session session = ((HibernateEntityManager)entityManager.unwrap(HibernateEntityManager.class)).getSession();
return session.createCriteria(filter.getClass()).add(Example.create(filter)).list();
}
}
BookedRoomDaoImpl.java :
package com.booking.dao.impl;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.booking.common.CommonUtils;
import com.booking.dao.BookedRoomDao;
import com.booking.dao.GenericDao;
import com.booking.member.vo.BookedRoom;
import com.booking.member.vo.Booking;
import com.booking.member.vo.TimeRange;
import org.hibernate.criterion.Restrictions;
#Repository("bookedRoomDao")
public class BookedRoomDaoImpl implements BookedRoomDao{
#PersistenceContext
EntityManager entityManager;
#Autowired
GenericDao<TimeRange,Long> timeRangeDao;
#Override
public List<BookedRoom> getBookedRooms(long id,String date){
List<BookedRoom> list = new ArrayList<BookedRoom>();
List<TimeRange> timeRanges = timeRangeDao.getAll(TimeRange.class);
for(TimeRange timeRange:timeRanges){
BookedRoom bookedRoom = new BookedRoom();
Booking booking = null;
try{
booking = (Booking)entityManager.createNativeQuery("select * from Booking b where b.time_range = ?1 and b.room = ?2 and date_format(date_booked,'%Y-%m-%d') = ?3",Booking.class)
.setParameter(1,timeRange.getId())
.setParameter(2,id)
.setParameter(3,date)
.getSingleResult();
}catch (NoResultException e) {
}
if(booking!=null){
bookedRoom.setBookingId(booking.getBookingId());
bookedRoom.setDateBooked(booking.getDateBooked());
bookedRoom.setRoomName(booking.getRoom().getRoomName());
bookedRoom.setUserName(booking.getUserid().getUsername());
if(booking.getUserid().getId()==CommonUtils.getCurrentUserProfile().getUserId()){
bookedRoom.setOwner(true);
}
}
bookedRoom.setFromTime(timeRange.getFromTime());
bookedRoom.setToTime(timeRange.getToTime());
bookedRoom.setTrId(timeRange.getId());
list.add(bookedRoom);
}
return list;
}
#Override
public void deleteBooking(long bookingId,long userId){
entityManager.createNativeQuery("delete from booking where booking_id=?1 and userid=?2")
.setParameter(1, bookingId)
.setParameter(2,userId)
.executeUpdate();
}
#Override
public List getBookingByRoomId(long roomId){
return entityManager.createNativeQuery("select * from booking where room = ?1",Booking.class)
.setParameter(1, roomId)
.getResultList();
}
}
And hibernate.cfg.xml :
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<validation-mode>NONE</validation-mode>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<!--value='create' to build a new database on each run; value='update' to modify an existing database; value='create-drop' means the same as 'create' but also drops tables when Hibernate closes; value='validate' makes no changes to the database-->
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.ejb.cfgfile" value="/resources/hibernate/hibernate.cfg.xml"/>
</properties>
</persistence-unit>
</persistence>
You need to add entityManagerFactory like this:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="jpaProperties" ref="hibernatePropertiesBean"/>
<property name="packagesToScan">
<list>
<value>your.packages</value>
</list>
</property>
</bean>
below is my spring-database.xml file. I can use sessionFactory in userDao. I also can use userDao in myUserDetailsService class. but when i try to use sessionFactory in registrationDao it gives me NullPointerException. same happens when i try to use registrationDao in registrationService service.
i am getting confused. please help.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<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/myds" />
<property name="username" value="root" />
<property name="password" value="mypass" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.findsuvidha.web.entity"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="userDao" class="com.findsuvidha.web.dao.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="myUserDetailsService" class="com.findsuvidha.web.service.MyUserDetailsService">
<property name="userDao" ref="userDao" />
</bean>
<bean id="registrationDao" class="com.findsuvidha.web.dao.RegistrationDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="registrationService" class="com.findsuvidha.web.service.RegistrationService">
<property name="registrationDao" ref="registrationDao" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true" />
<tx:method name="find*" read-only="true" />
<tx:method name="*" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="userServicePointCut"
expression="execution(* com.findsuvidha.web.service.*Service.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="userServicePointCut" />
</aop:config>
</beans>
Edit1:-Dao and DaoImpl which are able to use injected property
UserDao.java
package com.findsuvidha.web.dao;
import com.findsuvidha.web.entity.LoginMaster;
public interface UserDao {
LoginMaster findByUserName(String username);
}
UserDaoImpl.java
package com.findsuvidha.web.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.SessionFactory;
import com.findsuvidha.web.entity.LoginMaster;
public class UserDaoImpl implements UserDao {
private SessionFactory sessionFactory;
#SuppressWarnings("unchecked")
public LoginMaster findByUserName(String email) {
List<LoginMaster> users = new ArrayList<LoginMaster>();
users = getSessionFactory().getCurrentSession().createQuery("from LoginMaster where email=?")
.setParameter(0, email).list();
if (users.size() > 0) {
return users.get(0);
} else {
return null;
}
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
Dao and DaoImpl which are not able to use injected property
RegistrationDao.java
package com.findsuvidha.web.dao;
import com.findsuvidha.web.transferobject.NewUser;
public interface RegistrationDao {
void insertUser(NewUser user);
}
RegistrationDaoImpl.java
package com.findsuvidha.web.dao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.findsuvidha.web.entity.LoginMaster;
import com.findsuvidha.web.entity.UserDetail;
import com.findsuvidha.web.transferobject.NewUser;
public class RegistrationDaoImpl implements RegistrationDao{
private SessionFactory sessionFactory;
private LoginMaster loginUser = new LoginMaster();
private UserDetail userDetail = new UserDetail();
#Override
public void insertUser(NewUser user) {
System.out.println("entered dao impl");
userDetail.setEmail(user.getEmail());
userDetail.setFirstName(user.getFirstName());
userDetail.setLastName(user.getLastName());
userDetail.setMobileNo(user.getMobileNumber());
loginUser.setEmail(user.getEmail());
loginUser.setPassword(user.getPassword());
loginUser.setRoleFlag("ROLE_USR");
loginUser.setUserDetail(userDetail);
System.out.println("before session save");
getSessionFactory().getCurrentSession().save(loginUser);
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
I want to add object data and want to save in DB table, everything working fine but it gives me an error :
java.lang.NullPointerException
on line getSession().save(entity);
I have called this method in code :
#Service
public class AddCategoryProcessor implements ICommandProcessor<AddCategory> {
#Autowired
private IPatronCategoryRepository patronCategoryRepository = new PatronCategoryRepository();
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void Process(AddCategory command){
PatronCategory entity = new PatronCategory();
entity.setCategoryName(command.getCategoryName());
try
{
patronCategoryRepository.save(entity);
}catch (Exception e){
e.printStackTrace();
}
}
}
following is my xml file :
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://localhost:5432/abc"/>
<property name="username" value="postgres"/>
<property name="password" value="pwd"/>
<property name="validationQuery" value="SELECT 1"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.ngl.domain"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
<!-- Transaction Manager -->
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
Here is a getSession() method :
#Override
public Session getSession() {
return getSessionFactory().getCurrentSession();
}
Here is a sessionFactory declaration :
protected SessionFactory sessionFactory;
Any guesses why it's NULLPOINTEREXCEPTION ??
UPDATE :
java.lang.NullPointerException
at com.ngl.commandprocessors.patroncategoryprocessor.AddCategoryProcessor.Process(AddCategoryProcessor.java:32)
at com.ngl.commandprocessors.patroncategoryprocessor.AddCategoryProcessor.Process(AddCategoryProcessor.java:16)
at com.ngl.controllerapis.BaseApiController.ProcessRequest(BaseApiController.java:29)
at com.ngl.controllerapis.PatronCategoryController.addCategory(PatronCategoryController.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:746)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:687)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:822)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2441)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2430)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
and xml for transaction manager
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
in repository
#Autowired
protected SessionFactory sessionFactory;
Your config is a bit incomplete. You should delegate session management completely to Spring
Add in you spring xml file:
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Then, in your PatronCategoryRepository class, extend HibernateDaoSupport and add this constructor:
public class PatronCategoryRepository extends HibernateDaoSupport implements IPatronCategoryRepository{
#Autowired
public PatronCategoryRepository(HibernateTemplate hibernateTemplate) {
super();
super.setHibernateTemplate(hibernateTemplate);
}
[...]
}
In AddCategoryProcessor, leave the definition of the repository like this:
#Autowired
private IPatronCategoryRepository patronCategoryRepository;
And finally your method:
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void Process(AddCategory command){
PatronCategory entity = new PatronCategory();
entity.setCategoryName(command.getCategoryName());
try
{
getHibernateTemplate.save(entity);
}catch (Exception e){
e.printStackTrace();
}
}
In case you still need to access directy the SessionFactory, the only thing you have to do is inject it into PatronCategoryRepository:
#Repository
public class PatronCategoryRepository implements IPatronCategoryRepository{
#Autowired
protected SessionFactory sessionFactory;
public PatronCategoryRepository() {
}
public PatronCategory save(PatronCategory entity){
return getSession().save(entity);
}
private Session getSession() {
return sessionFactory.getCurrentSession();
}
}
And remember to remove the new clause from AddCategoryProcessor, leaving it like this:
#Autowired
private IPatronCategoryRepository patronCategoryRepository;
Employee.java
package com.javacodegeeks.snippets.enterprise.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "Employee1")
public class Employee implements Serializable {
#Id
#Column(name = "ID")
private int id;
#Column(name = "NAME")
private String name;
#Column(name = "AGE")
private int age;
public Employee() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
EmployeeDao.java
package com.javacodegeeks.snippets.enterprise.dao;
import com.javacodegeeks.snippets.enterprise.model.Employee;
public interface EmployeeDAO {
public void saveEmployee(Employee employee);
Employee findEmployeeById(int id);
void updateEmployee(Employee employee);
void deleteEmployee(Employee employee);
}
EmployeeDaoImpl.java
package com.javacodegeeks.snippets.enterprise.dao;
import java.io.Serializable;
import org.hibernate.SessionException;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.javacodegeeks.snippets.enterprise.model.Employee;
public class EmployeeDAOImpl implements EmployeeDAO {
private HibernateTemplate template;
private SessionFactory sessionFactory;
#Autowired
public void setTemplate(HibernateTemplate template) {
this.template = template;
// template.setSessionFactory(sessionFactory);
}
public void setSessionFactory(SessionFactory sessionFactory) {
new HibernateTemplate(sessionFactory);
}
/*
* public void saveEmployee(Employee employee) {
* sessionFactory.getCurrentSession().save(employee);
*
* }
*/
public Employee findEmployeeById(int id) {
return (Employee) sessionFactory.getCurrentSession().get(
Employee.class, id);
}
public void updateEmployee(Employee employee) {
sessionFactory.getCurrentSession().update(employee);
}
public void deleteEmployee(Employee employee) {
sessionFactory.getCurrentSession().delete(employee);
}
public void saveEmployee(Employee employee) {
sessionFactory.getCurrentSession().persist(employee);
template.saveOrUpdate(employee);
}
}
Application COntext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<context:component-scan base-package="com.javacodegeeks.snippets.enterprise.*" />
<!-- <tx:annotation-driven/> -->
<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/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>com.javacodegeeks.snippets.enterprise.model.Employee</value>
</list>
</property>
<!-- <property name="mappingResources">
<list>
<value>Employee.hbm.xml</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>
<!-- <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean> -->
<bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="d" class="com.javacodegeeks.snippets.enterprise.dao.EmployeeDAOImpl">
<property name="template" ref="template"></property>
</bean>
</beans>
pleas ehelp me :-)
I am using PrimeFaces 3.5, JSF 2.2, Hibernate 4.1, Spring 3.2.3, MySQL in my application.
Function updateUser() is supposed to update record in the database for the selected user from the PrimeFaces dataTable component(values are correct) but for some unknown reason it doesn't. I have a class named AbstractDAO which implements CRUD operations via generics. Insertion, selection and deleting works perfectly, but update fails without showing any errors at all. Any clues what can be wrong in my code?
applicationContext.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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<!-- GLOABL SETTINGS -->
<context:component-scan base-package="com.infostroy.adminportal"/>
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
<!-- DATA SOURCE AND PERSISTENCE SETTINGS -->
<bean id="propertiesPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:db.properties</value>
</list>
</property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dmDataSource"/>
<property name="packagesToScan" value="com.infostroy.adminportal"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${db.dialect}</prop>
<prop key="hibernate.show_sql">${db.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${db.hbm2ddl_auto}</prop>
<prop key="connection.pool_size">${db.pool_size}</prop>
<prop key="current_session_context_class">${db.current_session_context_class}</prop>
<prop key="org.hibernate.FlushMode">${db.flush_mode}</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="dataSource" ref="dmDataSource" />
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="dmDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${db.driver}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
<property name="maxWait" value="5000" />
<property name="initialSize" value="2" />
<property name="maxActive" value="100"/>
<property name="maxIdle" value="50"/>
<property name="minIdle" value="0"/>
</bean>
</beans>
db.properties:
db.username=root
db.password=root
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost/adminportal
db.pool_size=0
db.dialect=org.hibernate.dialect.MySQLDialect
db.hbm2ddl_auto=validate
db.show_sql=true
db.current_session_context_class=thread
db.flush_mode=COMMIT
AbstractDAO:
public abstract class AbstractDAO<T extends Serializable> implements Serializable {
#Autowired
protected SessionFactory sessionFactory;
protected T object;
protected Class clazz;
public AbstractDAO(Class clazz) {
this.clazz = clazz;
}
//Executes before being removed from container
#PreDestroy
protected void destroy() {
sessionFactory.getCurrentSession().close();
}
public Session getHiberSession() {
return sessionFactory.openSession();
}
#Transactional
protected T getByID(int id) {
String queryString = "from " + clazz.getSimpleName() + " where id = :id";
Query query = getHiberSession().createQuery(queryString);
query.setInteger("id", id);
object = (T) query.uniqueResult();
return object;
}
#Transactional
protected int deleteByID(int id) {
String queryString = "delete " + clazz.getSimpleName() + " where id = :id";
Query query = getHiberSession().createQuery(queryString);
query.setInteger("id", id);
return query.executeUpdate();
}
#Transactional
protected boolean insert(T object) {
try {
getHiberSession().save(object);
return true;
} catch (HibernateException ex) {
return false;
}
}
#Transactional
protected boolean update(T object) {
try {
getHiberSession().saveOrUpdate(object);
return true;
} catch (HibernateException ex) {
return false;
}
}
#Transactional
protected List getAllRecords() {
String queryString = "from " + clazz.getSimpleName();
Query query = getHiberSession().createQuery(queryString);
return query.list();
}
}
UserDAO.java:
#Repository
public class UserDAO extends AbstractDAO<User> {
public UserDAO() {
super(User.class);
}
public User getUserById(int id) {
return super.getByID(id);
}
public int deleteUserById(int id) {
return super.deleteByID(id);
}
public boolean insertUser(User user) {
return super.insert(user);
}
public boolean updateUser(User user) {
return super.update(user);
}
public List<User> getAllUsers() {
return super.getAllRecords();
}
}
If you need any additional info or code - just tell me. Every answer is highly appreciated and responded immidiately.
Thank you.
I'm just starting with Hibernate, but I'm using sessionFactory.getCurrentSession() instead of openSession().
After saveOrUpdate() mehod just flush the session. Ex: session.flush();
For more details you can see my blog here:
http://www.onlinetutorialspoint.com/hibernate/hibernate-example.html