MyEclipse Hibernate Spring tutorial – Managing Hibernate transaction in Spring
Spring transaction management, Hibernate transaction management in Spring
There was a problem/defect in the MyEclipse tutorial on Hibernate Spring. It was not a major problem. The tutorial demonstrates the Spring and Hibernate functionality pretty well. The only problem was that the code does seems to work properly. Because of absence of proper transaction management in code the data was not getting persisted in the database. Because of the caching in Hibernate it seems to the user that the data is being written to the database and then read back.
There are two solutions to the problem. One is to write the transaction management code in the java class itself. Another is to manage transaction via Spring’s transaction management. The second solution makes more sense because it shows of the Spring’s capability of managing transaction in Hibernate. You can see both the solutions here.
I am writing the Spring’s configuration for Hibernate transaction management again.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="configLocation" value="file:src/hibernate.cfg.xml"> </property> </bean> <bean id="userDAOTarget" class="com.myeclipse.hibernatespring.UserDAO"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <bean id="userDAOService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager" ref="transactionManager"/> <property name="transactionAttributes"> <props> <prop key="add*">PROPAGATION_REQUIRED</prop> <prop key="update*">PROPAGATION_REQUIRED</prop> <prop key="delete*">PROPAGATION_REQUIRED</prop> </props> </property> <property name="target"><ref local="persistenceLayer"/></property> </bean> <bean id="persistenceLayer" class="com.myeclipse.hibernatespring.PersistenceLayer" abstract="false" singleton="true" lazy-init="default" autowire="default" dependency-check="default"> <property name="userDAO"> <ref bean="userDAOTarget" /> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory"><ref bean="sessionFactory"/></property> </bean> </beans>