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.

<filter>
<filter-name>OpenViewInSession</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenViewInSession</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

Next configure the session factory in the spring context.

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.transaction.factory_class">
org.hibernate.transaction.JDBCTransactionFactory
</prop>
<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>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.supplyframe.partmanagement.domain.Company</value>
<value>com.supplyframe.partmanagement.domain.Taxonomy</value>
</list>
</property>
</bean>

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" 
    class="com.supplyframe.partmanagement.service.CompanyService">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>

Good luck!