Spring solves the problem of the closing and opening of Hibernate's session.
Hibernate allows lazy loading of associated objects, properties, but must ensure that deferred loading is limited to the same Hibernate Session range. If the Service layer returns a domain object that has the lazy load feature enabled to the Web layer, when the Web tier accesses data that requires lazy loading, the Hibernate Session that loads the realm object is closed, which causes the access exception to load the data lazily
(eg:org.hibernate.LazyInitializationException: (lazyinitializationexception.java:42)
-Failed to lazily initialize a collection of Role:cn.easyjava.bean.product.ProductType.childtypes, no session or session was closed
Org.hibernate.LazyInitializationException:failed to lazily initialize a collection of role: Cn.easyjava.bean.product.ProductType.childtypes, no session or session was closed)
The solution method can be used with filters or with interceptors
Method 1: Use Org.springframework.orm.hibernate4.support.OpenSessionInViewFilter to configure Opersessioninviewfilter in Web. Xml.
<filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class> Org.springframework.orm.hibernate4.support.OpenSessionInViewFilter </filter-class> <init-param> < Param-name>sessionfactorybeanname</param-name> <param-value>sessionFactory</param-value> </init-param> </filter> <filter-mapping> <filter-name>opensessioninviewfilter</ filter-name> <url-pattern>/*</url-pattern> </filter-mapping> Note: sessionfactiory is defined in Springcontext. Examples of Org.springframework.orm.hibernate4.LocalSessionFactoryBean (typically defined in appricationcontext.xml) Method Two: Using Org.springframework.orm.hibernate4.support.OpenSessionInViewInterceptor, set < in Appricationcontext.xml Bean name= "Opensessioninviewinterceptor" class= " Org.springframework.orm.hibernate4.support.OpenSessionInViewInterceptor "><property name=" Sessionfactory " ><ref bean= "Sessionfactory"/></property></bean><bean ID= "urlmapping" class= "org.springframework.web.servlet.handler.SimpleUrlHandlerMapping" ><property name= " Interceptors "><list><ref bean=" Opensessioninviewinterceptor "/></list></property>< Property name= "Mappings" ><value>/*</value> <!--URL to intercept--></property></bean>
Spring 3.x + hibernate4.x for data lazy loading