---
title: "(FlushMode.NEVER/MANUAL): Turn your Session into "
author: "H_eaven"
date: "2010-01-08T15:55:42Z"
tags: []
categories: ["企业架构"]
slug: "flushmode-never-manual-turn-your-session-into"
draft: false
lastmod: "2010-01-08T15:55:42Z"
id: 565921
url: "https://h-eaven.iteye.com/blog/565921"
---

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. 


执行这个方法得时候 出错了getHibernateTemplate().save(agentLog); 




错误原因: 
  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保护的方法有写权限，没受保护的则没有。