org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode

时间:2024-01-18 09:03:44

[spring]:org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode

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).如果是插入和修改操作,就不被允许的,所以报这个异常

查看spring中事务管理配置:

<bean id="txProxyTemplate" abstract="true"

class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">

<property name="transactionManager">

<ref bean="transactionManager" />

</property>

<property name="transactionAttributes">

<props>

<prop key="find*">PROPAGATION_REQUIRED</prop>

<prop key="save*">PROPAGATION_REQUIRED</prop>

<prop key="remove*">PROPAGATION_REQUIRED</prop>

<prop key="update*">PROPAGATION_REQUIRED</prop>

<prop key="create*">PROPAGATION_REQUIRED</prop>

<prop key="add*">PROPAGATION_REQUIRED</prop>

<prop key="del*">PROPAGATION_REQUIRED</prop>

<prop key="clear*">PROPAGATION_REQUIRED</prop>

<prop key="build*">PROPAGATION_REQUIRED</prop>

</props>

</property>

</bean>

看了之后才知道,原来的事务策略的<prop key="*">PROPAGATION_REQUIRED</prop>被删除后,bumenAuth()方法后忘了修改,所以导致报上述的错误

修改方法一:

将此方法修改为update或者build,add....等上述策略名称开头的方法:如:updateBumenAuth()

修改方法二:

增加<prop key="*">PROPAGATION_REQUIRED</prop>即可

修改方法三:

将web.xml下的

<filter>

<filter-name>OpenSessionInViewFilter</filter-name>

<filter-class>

org.springframework.orm.hibernate3.support.OpenSessionInViewFilter

</filter-class>

<init-param>

<param-name>singleSession</param-name>

<param-value>true</param-value>

</init-param>

</filter>

中 的singleSession值修改为false,即不限制整个过程用同一个session,但缺点是Hibernate Session的Instance可能会大增,使用的JDBC Connection量也会大增,如果Connection Pool的maxPoolSize设得太小,很容易就出问题

参考:关于OpenSessionView(http://liuwei1578.blog.163.com/blog/static/4958036420092104215514/)

Spring事务配置TransactionProxyFactoryBean(http://liuwei1578.blog.163.com/blog/static/49580364200921041136625/)