Search code examples
javaspringspring-mvclazy-initialization

LazyInitializationException occuring post introducing @Controller Annotation


We have a distributed web application implemented in Spring using Method Name Resolver. We are now migrating from Method Name Resolver to Spring Annotation (@Controller). Once we did that change, the big issue that we are facing is all the LAZY Initialization is not working. We started getting the below error:

2020-11-10 13:12:53,678 DEBUG     o.s.web.servlet.DispatcherServlet:1182 Handler execution resulted in exception - forwarding to resolved error view: ModelAndView: reference to view with name 'XXXXXXXX'; model is {XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:165) ~[hibernate-core-4.2.17.Final.jar:4.2.17.Final]
    at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:286) ~[hibernate-core-4.2.17.Final.jar:4.2.17.Final]
    at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185) ~[hibernate-core-4.2.17.Final.jar:4.2.17.Final]

On Analysis, we are able to find that, with the Method Name Resolver, System was able to Lazy Initialize the object. While in the @Controller annotation, System throws the LazyInitializationError, since the Session object is getting closed and not able to lazily initialize.

What could be the solution to overcome this? how to maintain the session through with the @Controller similar to Method name resolver.

Any insights will be highly apprecitated. Thanks.


Solution

  • Sounds like you are using the "Open Session In View" (anti-)pattern. Look at Spring's OpenSessionInViewFilter.