Tuesday, February 25, 2014

solved: Spring + Hibernate used with JPA and EntityManager => HibernateException: collection is not associated with any session

When I started using lazy loading in Spring + Hibernate project, I encounter this error.

What does NOT solve my issue:
  • @Transactional annotation
  • OpenSessionInViewInterceptor


The error message was:

HTTP ERROR 500

Problem accessing /user/1. Reason:
    Server Error

Caused by:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: collection is not associated with any session
 at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)


Solution for Spring with JPA approach and EntityManager, is to use OpenEntityManagerInViewFilter. Register it in web.xml this way:
<filter>
    <filter-name>
        OpenEntityManagerInViewFilter
    </filter-name>
    <filter-class>
        org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
    </filter-class>
    <init-param>
        <param-name>singleSession</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>flushMode</param-name>
        <param-value>AUTO</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>OpenEntityManagerInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>


Sources:
http://stackoverflow.com/questions/9304020/lazy-initialisation-with-openentitymanagerinviewfilter - not the selected answer, but this from Jhonathan

No comments:

Post a Comment