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).
Spring provides us with a opensessioninviewfilter filter that solves this problem very well. The main function of Opensessioninviewfilter is to bind a hibernate session and a line threads corresponding to a complete request process. The goal is to implement the "Open Session in View" mode. For example, it allows deferred loading of objects required to display after a transaction commits.
The Opensessioninviewfilter filter binds the Hibernate Session to the request thread, which is automatically detected by Spring's transaction manager. Therefore, the opensessioninviewfilter is suitable for the service layer environment using Hibernatetransactionmanager or Jtatransactionmanager for transaction management. It can also be used in non-transactional read-only data operations.
<filter>
<filter-name>spring opensessioninviewfilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<init-param>
<!--
Specifies the name of the Org.springframework.orm.hibernate3.LocalSessionFactoryBean in the spring configuration file, with the default value of Sessionfactory
If the name of Localsessionfactorybean in spring is not sessionfactory, the argument must be specified, otherwise the exception of sessionfactory cannot be found
-
<param-name>sessionFactoryBean</param-name>
<param-value>sessionFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>spring opensessioninviewfilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
The configuration and function of Opensessioninviewfilter