Open Session in View的作用

来源:互联网 发布:移动免流端口 编辑:程序博客网 时间:2024/06/13 06:23

原文地址:http://zhidao.baidu.com/question/104880914.html

首先要说明一下Open Session in View的作用,就是允许在每次的整个request的过程中使用同一个hibernate session,可以在这个request任
何时期lazy loading数据。
如果是singleSession=false的话,就不会在每次的整个request的过程中使用同一个hibernate session,而是每个数据访问都会产生各自的seesion,等于没有Open Session in View.
OpenSessionInViewFilter默认是不会对session 进行flush的,并且flush mode 是 never
代码:
protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
Session session = SessionFactoryUtils.getSession(sessionFactory, true);
session.setFlushMode(FlushMode.NEVER);
return session;
}
看getSession的方式就知道,把flush mode 设为FlushMode.NEVER,这样就算是commit的时候也不会session flush,
如果想在完成request过程中更新数据的话, 那就需要先把flush model设为FlushMode.AUTO,再在更新完数据后flush.
.
OpenSessionInView默认的FlushMode为
代码:
FlushMode.NEVER


::::::::::解决方法::::::::::::
可以采用spring的事务声明解决,示例代码如下:

<!-- 声明一个 Hibernate 3 的 事务管理器供代理类自动管理事务用-->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>

<aop:config>
<!-- 切入点指明了在执行com.ssh2.manager包中的所有方法时产生事务拦截操作 -->
<aop:pointcut id="daoMethods" expression="execution(* com.ssh2.manager.*.*(..))"/>
<!-- 定义了将采用何种拦截操作,这里引用到 txAdvice -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="daoMethods"/>
</aop:config>

<!-- 事务通知操作,使用的事务管理器引用自transactionManager -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 指定哪些方法需要加入事务 -->
<tx:method name="getPageTable*" propagation="REQUIRED"/>
<tx:method name="getTotalRecodes" propagation="REQUIRED"/>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>


原创粉丝点击