关于spring+hibernate的FlushMode的记录

参见hibernate的api说明https://www.hibernate.org/hib_docs/v3/api/org/hibernate/FlushMode.html

说明FlushMode有五种属性

NEVEL   

已经废弃了,被MANUAL取代了


2 MANUAL  

spring3.x中的opensessioninviewfilter已经将默认的FlushMode设置为MANUAL了;
如果FlushMode是MANUAL或NEVEL,在操作过程中hibernate会将事务设置为readonly,所以在增加、删除或修改操作过程中会出现如下错误
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;
解决办法网上有很多;
1 配置事务,spring会读取事务中的各种配置来覆盖hibernate的session中的FlushMode;
2 先编程式修改FlushMode,比如session.setFlushMode(FlushMode.AUTO); 这样hibernate就会自动去除readonly限制;
3 直接修改opensessioninviewfilter过滤器的配置,配置过滤器的时候配置
<filter>
      <filter-name>openSession</filter-name>
      <filter- class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter- class>
      <init-param>
          <param-name>flushMode</param-name>
          <param-value>AUTO</param-value>
      </init-param>
  </filter>

3 AUTO

设置成auto之后,当程序进行查询、提交事务或者调用session.flush()的时候,都会使缓存和数据库进行同步,也就是刷新数据库

4 COMMIT

提交事务或者session.flush()时,刷新数据库;查询不刷新


5 ALWAYS

每次进行查询、提交事务、session.flush()的时候都会刷数据库
这里需要说一下和AUTO的区别,当hibernate缓存中的对象被改动之后,会被标记为脏数据(即与数据库不同步了)。当session设置为FlushMode.AUTO时,hibernate在进行查询的时候会判断缓存中的数据是否为脏数据,是则刷数据库,不是则不刷,而always是直接刷新,不进行任何判断。很显然auto比always要高效得多。

转自:http://www.blogjava.net/landor2004/archive/2009/11/25/303701.html

猜你喜欢

转载自joinyo.iteye.com/blog/2264286