现在的位置: 首页 > 综合 > 正文

OpenSessionInView详解 转帖

2013年10月07日 ⁄ 综合 ⁄ 共 4842字 ⁄ 字号 评论关闭
OpenSessionInViewFilter是Spring提供的一个针对Hibernate的一个支持类,其主要意思是在发起一个页面请求时打开 Hibernate的Session,一直保持这个Session,直到这个请求结束,具体是通过一个Filter来实现的。

由于Hibernate引入了Lazy Load特性,使得脱离Hibernate的Session周期的对象如果再想通过getter方法取到其关联对象的值,Hibernate会抛出一个 LazyLoad的Exception。所以为了解决这个问题,Spring引入了这个Filter,使得Hibernate的Session的生命周期变长。

首先分析一下它的源码,可以发现,它所实现的功能其实比较简单:

Java代码
    1. SessionFactory sessionFactory = lookupSessionFactory(request);  
    2. Session session = null;  
    3. boolean participate = false;  
    4.   
    5. if (isSingleSession()) {  
    6.     // single session mode  
    7.     if (TransactionSynchronizationManager.hasResource(sessionFactory)) {  
    8.     // Do not modify the Session: just set the participate flag.  
    9.     participate = true;  
    10.        }    else {  
    11.     logger.debug("Opening single Hibernate Session in OpenSessionInViewFilter");  
    12.     session = getSession(sessionFactory);  
    13.     TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));  
    14.     }  
    15. else {  
    16.     // deferred close mode  
    17.     if (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) {  
    18. // Do not modify deferred close: just set the participate flag.  
    19.     participate = true;  
    20.     } else {  
    21.     SessionFactoryUtils.initDeferredClose(sessionFactory);  
    22.     }  
    23. }  
    24.   
    25. try {  
    26.     filterChain.doFilter(request, response);  
    27. finally {  
    28.     if (!participate) {  
    29.             if (isSingleSession()) {  
    30.                 // single session mode  
    31.         TransactionSynchronizationManager.unbindResource(sessionFactory);  
    32.         logger.debug("Closing single Hibernate Session in OpenSessionInViewFilter");  
    33.         closeSession(session, sessionFactory);  
    34.     }else {  
    35.         // deferred close mode  
    36.         SessionFactoryUtils.processDeferredClose(sessionFactory);  
    37.     }  
    38. }  
    39. }  
    40. SessionFactory sessionFactory = lookupSessionFactory(request);
    41. Session session = null;
    42. boolean participate = false;
    43. if (isSingleSession()) {
    44.     // single session mode
    45.     if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
    46.     // Do not modify the Session: just set the participate flag.
    47.     participate = true;
    48.        }    else {
    49.     logger.debug("Opening single Hibernate Session in OpenSessionInViewFilter");
    50.     session = getSession(sessionFactory);
    51.     TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
    52.     }
    53. else {
    54.     // deferred close mode
    55.     if (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) {
    56. // Do not modify deferred close: just set the participate flag.
    57.     participate = true;
    58.     } else {
    59.     SessionFactoryUtils.initDeferredClose(sessionFactory);
    60.     }
    61. }
    62. try {
    63.     filterChain.doFilter(request, response);
    64. finally {
    65.     if (!participate) {
    66.             if (isSingleSession()) {
    67.                 // single session mode
    68.         TransactionSynchronizationManager.unbindResource(sessionFactory);
    69.         logger.debug("Closing single Hibernate Session in OpenSessionInViewFilter");
    70.         closeSession(session, sessionFactory);
    71.     }else {
    72.         // deferred close mode
    73.         SessionFactoryUtils.processDeferredClose(sessionFactory);
    74.     }
    75. }
    76. }

    在上述代码中,首先获得SessionFactory,然后通过SessionFactory获得一个Session。然后执行真正的Action代码,最后根据情况将Hibernate的Session进行关闭。整个思路比较清晰。

    注意,在这里有个2个Tips:
    1)通过getSession()获得的这个Session做了一次
    session.setFlushMode(FlushMode.NEVER); 有关FlushMode可以参考一下这篇文章。http://www2.matrix.org.cn/resource/article/2006-10-08/Hibernate+FlushMode+NEVER_312bca85-5699-11db-91a0-d98dff0aec60.html
    2)Spring对拿到的Session做了一次绑定到当前线程的做法,使得这个Session是线程安全的。

    从上述代码其实可以得到一些对我们的开发有帮助的结论:
    1)如果使用了OpenSessionInView模式,那么Spring会帮助你管理Session的开和关,从而你在你的DAO中通过 HibernateDaoSupport拿到的getSession()方法,都是绑定到当前线程的线程安全的Session,即拿即用,最后会由 Filter统一关闭。
    2)由于拿到的Hibernate的Session被设置了session.setFlushMode(FlushMode.NEVER); 所以,除非你直接调用session.flush(),否则Hibernate session无论何时也不会flush任何的状态变化到数据库。因此,数据库事务的配置非常重要。(我们知道,在调用 org.hibernate.Transaction.commit()的时候会触发session.flush())我曾经见过很多人在使用 OpenSessionInView模式时,都因为没有正确配置事务,导致了底层会抛出有关FlushMode.NEVER的异常。

    OpenSessionInView这个模式使用比较简单,也成为了大家在Web开发中经常使用的方法,不过它有时候会带来一些意想不到的问题,这也是在开发中需要注意的。
    1. 在Struts+Spring+Hibernate环境中,由于配置的问题导致的模式失效
    这个问题以前论坛曾经讨论过,可以参考一下下面这个帖子:
    http://www.javaeye.com/topic/15057

    2. OpenSessionInView的效率问题
    这个问题也有人在论坛提出过,Robbin曾经做过具体的测试,可以具体参考一下下面这个帖子:
    http://www.javaeye.com/topic/17501

    3. 由于使用了OpenSessionInView模式后造成了内存和数据库连接问题
    这个问题是我在生产环境中碰到的一个问题。由于使用了OpenSessionInView模式,Session的生命周期变得非常长。虽然解决了 Lazy Load的问题,但是带来的问题就是Hibernate的一级缓存,也就是Session级别的缓存的生命周期会变得非常长,那么如果你在你的 Service层做大批量的数据操作时,其实这些数据会在缓存中保留一份,这是非常耗费内存的。还有一个数据库连接的问题,存在的原因在于由于数据库的 Connection是和Session绑在一起的,所以,Connection也会得不到及时的释放。因而当系统出现业务非常繁忙,而计算量又非常大的时候,往往数据连接池的连接数会不够。这个问题我至今非常头痛,因为有很多客户对数据连接池的数量会有限制,不会给你无限制的增加下去。

    4. 使用了OpenSessionInView模式以后取数据的事务问题
    在使用了OpenSessionInView以后,其实事务的生命周期比Session的生命周期来得短,就以为着,其实有相当一部分的查询是不被纳入到事务的范围内的,此时是否会读到脏数据?这个问题我至今不敢确认,有经验的朋友请指教一下。

    最后提一下OpenSessionInView模式的一些替代方案,可以使用OpenSessionInViewInterceptor来代替这个Filter,此时可以使用Spring的AOP配置,将这个Interceptor配置到你所需要的层次上去。另外就是只能使用最古老的 Hibernate.initialize()方法进行初始化了。

抱歉!评论已关闭.