NEVER
public static final FlushMode NEVER
-
Deprecated.
use
MANUAL
instead. -
The
Session
is never flushed unlessSession.flush()
is explicitly called by the application. This mode is very efficient for read only transactions.
MANUAL
public static final FlushMode MANUAL
-
The
Session
is only ever flushed whenSession.flush()
is explicitly called by the application. This mode is very efficient for read only transactions.
COMMIT
public static final FlushMode COMMIT
-
The
Session
is flushed whenTransaction.commit()
is called.
AUTO
public static final FlushMode AUTO
-
The
Session
is sometimes flushed before query execution in order to ensure that queries never return stale state. This is the default flush mode.
ALWAYS
public static final FlushMode ALWAYS
The Session
is flushed before every query. This is almost always unnecessary and inefficient.
1、NEVER
已经废弃了,被MANUAL取代了
2、MANUAL
spring3.x中的opensessioninviewfilter已经将默认的FlushMode设置为MANUAL了;如果FlushMode是MANUAL或NEVER,在操作过程中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是直接刷新,不进行任何判断。