错误场景:
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>