Spring+Hibernate报错:Write operations are not allowed in read-only mode (FlushMode.NEVER/MANUAL)

错误场景:


applicationContext.xml文件中配置如下:

<!-- 1.配置事务管理器 -->
<bean id="transManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>

<!-- 2.配置事务通知  只有save、update、delete开头的方法才可以对数据库进行增删改操作-->
  <tx:advice id="txAdvice" transaction-manager="transManager">
  <tx:attributes>
  <tx:method name="save*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
  <tx:method name="update*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
  <tx:method name="delete*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/> 
  <tx:method name="*" read-only="true" />
  </tx:attributes>
  </tx:advice>


但是在   this.getHibernateTemplate().save()等方法时报错:

Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.

后经查找发现错误原因如下:


在项目web.xml文件中,我做了如下配置:

<!-- 配置OpenSessionInViewFilter过滤器,可以解决项目中出现的懒加载问题 -->
  <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>/*</url-pattern>
  </filter-mapping>

这个配置是为了解决懒加载异常但是在开启OpenSessionInViewFilter这个过滤器的时候FlushMode会被默认设置为了MANUAL,如果FlushMode是MANUAL或NEVEL,在操作过程中 hibernate会将事务设置为readonly,所以在增加、删除或修改操作过程中都会出现该错误,此时,只要在那个filter里面加上如下代码就能解决问题:

<init-param>  
           <param-name>flushMode</param-name>  
           <param-value>AUTO</param-value>  
    </init-param>





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值