由于Spring控制的Hibernate的生命周期只針對數(shù)據(jù)層和服務層,而未管理到表現(xiàn)層,所以在表現(xiàn)層使用延時加載會出現(xiàn)the owning Session was closed或者no session or session was closed的異常信息。針對這一點,可以通過hibernate filter的方式來解決。
在WEB.xml文件中配置filter.
<!-- hibernate session filter -->
<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>*.do</url-pattern>
</filter-mapping>
我們的系統(tǒng)架構(gòu)是struts+spring+hibernate,struts跟spring的整合是在struts-config.xml里加了個plugin<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>*.do</url-pattern>
</filter-mapping>
<plug-in
className="org.springframework.WEB.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation"
value="/WEB-INF/classes/applicationContext.xml" />

</plug-in>
className="org.springframework.WEB.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation"
value="/WEB-INF/classes/applicationContext.xml" />

</plug-in>
在WEB.xml中配置hibernateFilter 后,還需要在struts-config.xml里把plugin去掉,在WEB.xml里加上如下代碼:
<!--Spring ApplicationContext-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
這樣配置之后如果沒有配置事務,是有問題的。不能進行update和insert操作了。
怎么辦呢?只需要在filter中加入一個參數(shù)
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
就可以了,當然這樣 每次訪問dao都會新開個session,對性能的影響還是比較大的。最好的辦法當然是配置事務了。<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>