---
title: "Write operations are not allowed in read-only mode"
author: "小牛犊"
date: "2008-09-23T13:57:57Z"
tags: ["Bean", "Blog", "DAO", "Security", "Spring"]
slug: "write-operations-are-not-allowed-in-read-only-mode"
draft: false
lastmod: "2008-09-23T13:57:57Z"
id: 245859
url: "https://xiaoniudu2008.iteye.com/blog/245859"
---

转载：[http://hi.baidu.com/gzwfdy/blog/item/39dc13cb20593f1bbe09e65f.html](http://hi.baidu.com/gzwfdy/blog/item/39dc13cb20593f1bbe09e65f.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  
错误原因:  
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](http://calvin.blog.javascud.org/post/46.htm)  
解决办法:  
采用spring的事务声明,使方法受transaction控制  
&lt;bean id="baseTransaction"  
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"  
abstract="true"&gt;  
&lt;property name="transactionManager" ref="transactionManager"/&gt;  
&lt;property name="proxyTargetClass" value="true"/&gt;  
&lt;property name="transactionAttributes"&gt;  
&lt;props&gt;  
&lt;prop key="get\*"&gt;PROPAGATION\_REQUIRED,readOnly&lt;/prop&gt;  
&lt;prop key="find\*"&gt;PROPAGATION\_REQUIRED,readOnly&lt;/prop&gt;  
&lt;prop key="load\*"&gt;PROPAGATION\_REQUIRED,readOnly&lt;/prop&gt;  
&lt;prop key="save\*"&gt;PROPAGATION\_REQUIRED&lt;/prop&gt;  
&lt;prop key="add\*"&gt;PROPAGATION\_REQUIRED&lt;/prop&gt;  
&lt;prop key="update\*"&gt;PROPAGATION\_REQUIRED&lt;/prop&gt;  
&lt;prop key="remove\*"&gt;PROPAGATION\_REQUIRED&lt;/prop&gt;  
&lt;/props&gt;  
&lt;/property&gt;  
&lt;/bean&gt;  
    &lt;bean id="userService" parent="baseTransaction"&gt;  
&lt;property name="target"&gt;  
&lt;bean class="com.phopesoft.security.service.impl.UserServiceImpl"/&gt;  
&lt;/property&gt;  
&lt;/bean&gt;