由于Spring控制的Hibernate的生命周期只針對(duì)數(shù)據(jù)層和服務(wù)層,而未管理到表現(xiàn)層,所以在表現(xiàn)層使用延時(shí)加載會(huì)出現(xiàn)the owning Session was closed或者no session or session was closed的異常信息。針對(duì)這一點(diǎn),可以通過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里加了個(gè)plugin
<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>
這樣配置之后如果沒有配置事務(wù),是有問題的。不能進(jìn)行update和insert操作了。
怎么辦呢?只需要在filter中加入一個(gè)參數(shù)
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
就可以了,當(dāng)然這樣 每次訪問dao都會(huì)新開個(gè)session,對(duì)性能的影響還是比較大的。最好的辦法當(dāng)然是配置事務(wù)了。