I face a problem with Spring3 and Hibernate4. I would like to use @Transactional to manage hibernate transactions. My JUnit test works with HSQDB. But when deployed on Tomcat, an exception occures.
I tried many configurations, and the one which works with unit testing consists in deleting hibernate.current_session_context_class property in session factory configuration. Then in server mode, the exception below occures :
org.hibernate.HibernateException: No Session found for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:990)
at myproject.dao.impl.UserDaoImpl.create(UserDaoImpl.java:37)
When I configure hibernate.current_session_context_class to value "thread", then the exception is :
org.hibernate.HibernateException: save is not valid without active transaction
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:348)
at com.sun.proxy.$Proxy25.save(Unknown Source)
at myproject.dao.impl.UserDaoImpl.create(UserDaoImpl.java:39)
Here is my configuration :
<beans>
<context:annotation-config />
<tx:annotation-driven transaction-manager="transactionManager"/>
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/MyDataSource"/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>myproject.dao.entity</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.connection.pool_size">1</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>