原因:
它有两种配置方式OpenSessionInViewInterce
Open Session In View在request把session绑定到当前thread期间一直保持hibernate session在open状态,使session在request的整个期间都可以使用,如在View层里PO也可以lazy loading数据,如 ${ company.employees }。当View 层逻辑完成后,才会通过Filter的doFilter方法或Interceptor的postHandle方法自动关闭session。
解决方案:
我实践过,这个filter写在strutsfilter最前面保险
在 web.xml配置里添加
<filter> <filter-name>OpenSessionInViewFilter</filter-name>
<filter-class> org.springframework.orm.hibernate3.support.OpenSessionInViewFilter </filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
<init-param> <param-name>singleSession</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name> flushMode </param-name> <param-value>AUTO </param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2.使用Spring提供的Open Session In View而引起Write operations are not allowed in read-only mode (FlushMode.NEVER) 错误解决:
当你配好OpenSessionInViewFilter后,但是你在beans.xml中没写上事务的话,就会出现上面的那个错误,即没配下面的事务
这是因为当你没配事务的话,OpenSessionInViewFilter认为你将事务配置为了read-only,所以当你在dao层调用save方法的时候,就save不进去,出现了Write operations are not allowed,这时候你可以由三种方法来去除这个异常,
(1)当然是配上事务,即上面的那个图
(2)去除OpenSessionInViewFilter,也可以去除这个错误
(3)在OpenSessionInViewFilter中加上下面两个属性就行了
<init-param>
<param-name> flushMode </param-name>
<param-value>AUTO </param-value>
</init-param>