Christoph Ehscheidt

code and fly

Thoughts, stories and ideas.


spring-webmvc, hibernate jpa and lazy loading

Hi again,

another thing I found while using spring and other web technologies:

When you try to display entities which are connected to other entities in a web view you should consider to use eager loading fetch strategies.

If you want to fetch depending entities lazy you most probably will see a LazyInitializationException (LIE).

A workaround is to use the OpenSessionInView (OSIV) Pattern to let spring initialize a valid session when rendering the view. To do this with spring configured with JPA add the following to your web.xml:

<filter>
  <filter-name>OpenEntityManagerInViewFilter</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>OpenEntityManagerInViewFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

Cheers

comments powered by Disqus