Archive for the ‘Development’ Category

Integrating Spring and Hibernate would seem like a no brainier. Spring comes with a plethora of support for hibernate and the combination is very popular.  However, I’ve struggled every time to figure out how to best integrate the two technologies.  I’ve searched Google and found as many different solutions as new questions.

The problem seems to stem from the different patterns available to intergrate spring and hibernate. The complexity of your application will help determine which pattern works best.  For most web based application session-per-request pattern is sufficient.  A session-per-request is a single hibernate session for each http request.  Spring provides a servlet filter for this, OpenSessionInViewFilter.  This filter binds a hibernate session to thread local when the filter processes the request.

To set up the OpenSessionInViewFilter add the following to the web.xml file.


Next configure the session factory in the spring context.

<bean id="sessionFactory"
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<prop key="hibernate.transaction.factory_class">
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<!-- this will show us all sql statements -->
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.show_type">false</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</prop>
<prop key="hibernate.hibernate.cache.use_query_cache">true</prop>
<!-- Set schema here so we can vary it -->
<prop key="hibernate.default_schema">cms</prop>
<property name="annotatedClasses">

Now inject the session factory configured previously into you data access classes. It’s important to call currentSession() on the session factory when a session is needed and not store the session. The session returned by currentSession() will be the session bound to thread local when the filter processed the request.

<bean id="companyService" 
<property name="sessionFactory" ref="sessionFactory"></property>

Good luck!