OpenEntityManagerInViewFilter

Aug 16, 2010   #hibernate  #java  #spring 

When using Spring and Hibernate you may be facing org.hibernate.LazyInitializationExceptions because your view has no open database session. You may often see the recommendation to use an OpenSessionInViewFilter to cope with this problem. But what if you are using an EntityManager rather than a session? Just use the OpenEntityManagerInViewFilter instead!

Here is how to do it:

     <filter>
         <filter-name>openEntityManagerFilter</filter-name>
          <filter-class>
              org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
          </filter-class>
          <init-param>
              <param-name>entityManagerFactoryBeanName</param-name>
              <param-value>entityManagerFactory</param-value>
          </init-param>
      </filter>
 
      <filter-mapping>
          <filter-name>openEntityManagerFilter</filter-name>
          <url-pattern>/requestPathToApplyFilterTo/*</url-pattern>
      </filter-mapping>

DISCLAIMER: While being an easy way to avoid org.hibernate.LazyInitializationExceptions, using an open database connection in view pattern is not always a good solution when it comes to performance and memory efficency. Use with care!