`
nieli
  • 浏览: 82837 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Write operations are not allowed in read-only mode问题处理

    博客分类:
  • java
阅读更多

参考自:

http://hi.baidu.com/woiwojia/blog/item/08755f032f75607e3812bb8c.html

http://blog.sina.com.cn/s/blog_5dc12c490100crr5.html

 

错误代码:
org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.NEVER) - turn your Session into FlushMode.AUTO or remove 'readOnly' marker from transaction definition
错误原因:
这是因为使用Spring提供的Open Session In View而引起的问题,OpenSessionInViewFilter在getSession的时候,会把获取回来的session的flush mode 设为FlushMode.NEVER。然后把该sessionFactory绑定到TransactionSynchronizationManager,使request的整个过程都使用同一个session,在请求过后再接除该sessionFactory的绑定,最后closeSessionIfNecessary根据该session是否已和transaction绑定来决定是否关闭session。在这个过程中,若HibernateTemplate 发现自当前session有不是readOnly的transaction,就会获取到FlushMode.AUTO Session,使方法拥有写权限。
也即是,如果有不是readOnly的transaction就可以由Flush.NEVER转为Flush.AUTO,拥有insert,update,delete操作权限,如果没有transaction,并且没有另外人为地设flush model的话,则doFilter的整个过程都是Flush.NEVER。所以受transaction保护的方法有写权限,没受保护的则没有
解决办法:
采用spring的事务声明,使所有service方法受transaction控制

<!-- Spring2.0的事务管理 -->
 <bean id="transactionManager"
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory">
   <ref local="sessionFactory" />
  </property>
 </bean>
 <tx:advice id="txtAdvice"
  transaction-manager="transactionManager" >
  <tx:attributes>
   <tx:method name="add*" propagation="REQUIRED" />
   <tx:method name="save*" propagation="REQUIRED" />
   <tx:method name="update*" propagation="REQUIRED" />
   <tx:method name="delete*" propagation="REQUIRED" />
   <tx:method name="find*" propagation="REQUIRED"
    read-only="true" />
   <tx:method name="get*" propagation="REQUIRED"
    read-only="true" />
   <tx:method name="search*" propagation="REQUIRED"
    read-only="true" />
   <tx:method name="*" propagation="REQUIRED" />
  </tx:attributes>
 </tx:advice>

 <aop:config proxy-target-class="true">
  <aop:pointcut id="serviceMethods"
   expression="execution(* com.service.*.*(..))" />
  <aop:pointcut id="baseServiceMethods"
   expression="execution(* com.base.service.*.*(..))" />
  <aop:advisor advice-ref="txtAdvice"
   pointcut-ref="serviceMethods" />
  <aop:advisor advice-ref="txtAdvice"
   pointcut-ref="baseServiceMethods" />

  <!--使不同包下的service方法都受事务管理-->
 </aop:config>

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics