November 10, 2008

at Monday, November 10, 2008 Posted by Billy

I am creating a Java web application using Spring and Hibernate. Although I clearly see the benefit of using the Spring framework and Hibernate object/relational mapping tool, configuring it properly can cause some headaches.

Recently I was using Spring's HibernateTemplate to retrieve a list of users from my database. After successfully running a simple query, I then wanted to return the users starting at result number 10 instead of 0. I scanned HibernateTemplate's api to no avail, then searched Google and, to my surprise, found there was no way to return specific rows using HibernateTemplate. The forum posts suggested using Hibernate session instead.

I added a SessionFactory to my class and changed my query code to something like this:

return sessionFactory.getCurrentSession().createQuery("FROM User")
.setMaxResults(10).setFirstResult(10).list();


I confidently ran the code and received the following error:

- Method execution failed:
org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here



This error happened because I did not have my transaction managment configured properly. HibernateTemplate handles this on its own, but when using Hibernate sessions directly, put something like this in your Spring bean files:
 <!-- enable the configuration of transactional behavior based on annotations -->  
<tx:annotation-driven />

<!-- a PlatformTransactionManager is still required -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>


More information can be found in the Spring documentation.

0 comments: