When using the Load method in Hibernate, the session is closed when the data is not actually fetched, and when we really want to get the data, it forces load to load the data, and the session is closed, so an exception occurs. Typically, in the MVC pattern, when we call the persistence layer in the M layer to fetch the data (the persistence layer uses the Load method to load the data), when the call ends, the session closes, and we want to use the data at the V level to force load to load the data. We hope that this session is open, this is the so-called open session in view. We can use filter to achieve this, or we can do it with interceptor.
Filter
?
<!--spring Opensessioninview Implementation This listener should be in front of the struts2 listener--
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>
Org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Interceptor:
?
Importorg.springframework.orm.hibernate3.support.HibernateDaoSupport;
Publicclassxxxdaoextendshibernatedaosupport {
Publicvoidsave (Xxx transientinstance) {
try{
Gethibernatetemplate (). Save (Transientinstance);
}catch (RuntimeException re) {
Throwre;
}
}
}
The main function of Opensessioninviewfilter is to bind a hibernate session and a line threads corresponding to a complete request process. Open session in view keeps hibernate session open during request binding session to the current thread, so that the session can be used throughout the request. As in the view Layer PO can also be lazy loading data, such as ${company.employees}. When the view layer logic is complete, the session is automatically closed via the filter's Dofilter method or Interceptor's Posthandle method.
In addition,<url-pattern>/*</url-pattern> best not write/*, because in this case, access to all the URL will open a session for it, resulting in performance degradation;
[Turn]java frame Spring Opensessioninview What's the role