错误:Write operations are not allowed in read-only mode (FlushMode.NEVER和could not initiallize proxy -

来源:互联网 发布:网络订餐 方便面 编辑:程序博客网 时间:2024/06/16 21:59


原因:      

     在没有使用Spring提供的Open Session In View情况下,因需要在service(or Dao)层里把session关闭,所以lazy loading 为true的话,要在应用层内把关系集合都初始化,如 company.getEmployees(),否则Hibernate抛session already closed Exception;    Open Session In View提供了一种简便的方法,较好地解决了lazy loading问题.

它有两种配置方式OpenSessionInViewInterceptor和OpenSessionInViewFilter(具体参看SpringSide),功能相同,只是一个在web.xml配置,另一个在application.xml配置而已。

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> 



原创粉丝点击