S2SH集成 OpenSessionInViewFilter 出错

来源:互联网 发布:sigma化妆刷 淘宝授权 编辑:程序博客网 时间:2024/05/16 06:54
         错误:

Write operations are not allowed in read-only mode (FlushMode.NEVER) - turn your Session into FlushMode.AUTO or remove 'readOnly' marker from transaction definition

Write operations are not allowed in read-only mode (FlushMode.NEVER/MANUAL): Turn your Session into FlushMode.COMMIT/AU

org.springframework.dao.InvalidDataAccessApiUsageException: Write

operations are not allowed in read-only mode

(FlushMode.NEVER/MANUAL): Turn your Session into

FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction

definition.
at

org.springframework.orm.hibernate3.HibernateTemplate.checkWriteOper

ationAllowed(HibernateTemplate.java:1095)

这个异常产生的主要原因是DAO采用了Spring容器的事务管理策略,如果操作方法的名称和事务策略中指定的被管理的名称不能够匹配上,spring 就会采取默认的事务管理策略(PROPAGATION_REQUIRED,read only).如果是插入和修改操作,就不被允许的,所以包这个异常


1.

错误原因:

  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保护的方法有写权限,没受保护的则没有。

参考文章:

  http://calvin.blog.javascud.org/post/46.htm

解决办法:

  采用spring的事务声明,使方法受transaction控制

<!--配置事务的传播特性-->
 <tx:advice id="txAdvice" transaction-manager="transactionManager">
  <tx:attributes>
   <tx:method name="save*" propagation="REQUIRED"/>
   <tx:method name="add*" propagation="REQUIRED"/>
   <tx:method name="update*" propagation="REQUIRED"/>
   <tx:method name="delete*" propagation="REQUIRED"/>
   <tx:method name="*" propagation="REQUIRED" read-only="true"/>
  </tx:attributes>
 </tx:advice>


 

2.一般这个错误是事务引起的,如果确定事务没有问题,还是有这个错,可以重写OpenSessionInViewFilter的2个方法
     public class OpenSessionInViewFilter extends org.springframework.orm.hibernate3.support.OpenSessionInViewFilter {
      
        /**
         * we do a different flushmode than in the codebase
         * here
         */
        protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
                Session session = SessionFactoryUtils.getSession(sessionFactory, true);
                session.setFlushMode(FlushMode.COMMIT);
                return session;
        }
        /**
         * we do an explicit flush here just in case
         * we do not have an automated flush
         */
        protected void closeSession(Session session, SessionFactory factory) {
                session.flush();
                super.closeSession(session, factory);
        }
}