Spring+Hibernate中OpenSessionInView模式运用
中会在Update Domain Object时遇到
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异常问题,这个Exception在尚未进入DAO时就会遇到,是一个会发生在Modify Domain Object时的问题。
可能的解決方式有:
1、将singleSession设为false,这样只要改web.xml,缺点是Hibernate Session的Instance可能会大增,使用的JDBC Connection量也会大增,如果Connection Pool的maxPoolSize设得太小,很容易就出问题。
2、在控制器中自行管理Session的FlushMode,麻烦的是每个有Modify的Method都要多几行程式。
session.setFlushMode(FlushMode.AUTO);
session.update(user);
session.flush(); 
3、Extend OpenSessionInViewFilter,Override protected Session getSession(SessionFactory sessionFactory),将FlushMode直接改为Auto。
4、让方法受Spring的事务控制。
下面着重解说第4种方式:
OpenSessionInViewFilter里的几个方法:
protected void doFilterInternal(HttpServletRequest request,

HttpServletResponse response,FilterChain filterChain) throws ServletException, IOException
{
SessionFactory sessionFactory = lookupSessionFactory();
logger.debug("Opening Hibernate Session in OpenSessionInViewFilter");
Session session = getSession(sessionFactory); TransactionSynchronizationManager.bindResource(
sessionFactory, new SessionHolder(session));

try
{
filterChain.doFilter(request, response);

} finally
{
TransactionSynchronizationManager.unbindResource(sessionFactory);
logger.debug("Closing Hibernate Session in OpenSessionInViewFilter");
closeSession(session, sessionFactory);
}
}

protected Session getSession(SessionFactory sessionFactory)

throws DataAccessResourceFailureException
{
Session session = SessionFactoryUtils.getSession(sessionFactory, true);
session.setFlushMode(FlushMode.NEVER);
return session;
}
protected void closeSession(Session session, SessionFactory sessionFactory)

throws CleanupFailureDataAccessException
{
SessionFactoryUtils.closeSessionIfNecessary(session, sessionFactory);
} 可以看到OpenSessionInViewFilter在getSession的时候,会把获取回来的session的flush mode 设为FlushMode.NEVER。然后把该sessionFactory绑定到TransactionSynchronizationManager,使request的整个过程都使用同一个session,在请求过后再解除该sessionFactory的绑定,最后closeSessionIfNecessary根据该session是否已和transaction绑定来决定是否关闭session。在这个过程中,若HibernateTemplate 发现自当前session有不是readOnly的transaction,就会获取到FlushMode.AUTO Session,使方法拥有写权限:

public static void closeSessionIfNecessary(Session session, SessionFactory sessionFactory) throws CleanupFailureDataAccessException
{

if (session == null || TransactionSynchronizationManager.hasResource(sessionFactory))
{
return;
}
logger.debug("Closing Hibernate session");

try
{
session.close();
}

catch (JDBCException ex)
{
throw new CleanupFailureDataAccessException("Could not close Hibernate session", ex.getSQLException());

} catch (HibernateException ex)
{
throw new CleanupFailureDataAccessException("Could not close Hibernate session", ex);
}
} 如果有不是readOnly的transaction就可以由Flush.NEVER转为Flush.AUTO,拥有insert,update,delete操作权限,如果没有transaction,并且没有另外人为地设flush model的话,则doFilter的整个过程都是Flush.NEVER。所以受transaction保护的方法有写权限,没受保护的则没有。
采用spring的事务声明,使方法受transaction控制:
<bean id="manager" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="proxyInterfaces">
<list>
<value>com.zhupan.service.IManager</value>
</list>
</property>
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<property name="target">
<ref local="managerTarget" />
</property>
<property name="transactionAttributes">
<props>
<prop key="*Insert">PROPAGATION_REQUIRED</prop>
<prop key="*Update">PROPAGATION_REQUIRED</prop>
<prop key="*Get*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="*List*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>对于上面的,以Insert,Update结尾的方法拥有可写的事务,如果某个方法,如方法名为savaSort(),则没有写权限,这时若此方法内有insert,update,delete操作的话,则需要手动设置flush model为Flush.AUTO,如:
session.setFlushMode(FlushMode.AUTO);
session.update(user);
session.flush();
