新Hibernate SessionFactory().getCurrentSession()猫腻

转自http://liusu.iteye.com/blog/380397


今天要用Hibernate做点实验,下载最新版得下来。解压,建项目,从tutorial copy代码。Tutorial里面提到说最新的Hibernate已经不需要用户自己使用ThreadLocal得方式来管理和持有session,而把这种session管理方式内置了,只要依据依据配置就可以用了 

Java代码   收藏代码
  1. hibernate.current_session_context_class = jta/thread/managed //Use thread  


HibernateUtil.java 
Java代码   收藏代码
  1. package org.hibernate.tutorial.util;  
  2.   
  3. import org.hibernate.SessionFactory;  
  4. import org.hibernate.cfg.Configuration;  
  5.   
  6. public class HibernateUtil {  
  7.   
  8.     private static final SessionFactory sessionFactory;  
  9.   
  10.     static {  
  11.         try {  
  12.             // Create the SessionFactory from hibernate.cfg.xml  
  13.             sessionFactory = new Configuration().configure().buildSessionFactory();  
  14.         } catch (Throwable ex) {  
  15.             // Make sure you log the exception, as it might be swallowed  
  16.             System.err.println("Initial SessionFactory creation failed." + ex);  
  17.             throw new ExceptionInInitializerError(ex);  
  18.         }  
  19.     }  
  20.   
  21.     public static SessionFactory getSessionFactory() {  
  22.         return sessionFactory;  
  23.     }  
  24.   
  25. }  


在使用的时候大概都是如此调用: 

Java代码   收藏代码
  1. private Long createAndStoreEvent(String title, Date theDate) {  
  2.   
  3.     Session session = HibernateUtil.getSessionFactory().getCurrentSession();  
  4.     session.beginTransaction();  
  5.   
  6.     Event theEvent = new Event();  
  7.     theEvent.setTitle(title);  
  8.     theEvent.setDate(theDate);  
  9.   
  10.     session.save(theEvent);  
  11.   
  12.     session.getTransaction().commit();  
  13.   
  14.     return theEvent.getId();  
  15. }  

很顺利,跑起来也一切正常。 我有一个查询的需求。就是load一个Object对象需求。代码如下: 
Java代码   收藏代码
  1. private Event find(Event event) {  
  2.     Session session = HibernateUtil.getSessionFactory().getCurrentSession();  
  3.     //session.beginTransaction();  
  4.   
  5.     Event load = (Event) session.load(Event.class, event.getId());  
  6.   
  7.     //session.getTransaction().commit();  
  8.   
  9.     return load;  
  10. }  

我一想,就是一普通的load和查询操作,应该不用开闭Transaction了。但是却报异常了: 

Java代码   收藏代码
  1. org.hibernate.HibernateException: get is not valid without active transaction  


太抓狂了,就一些查询操作也要开闭Transaction。公司有使用过Hiberbate的小伙子说的记得应该是不用的。想想唯一的使用的区别就是得到Session的代码从 

Java代码   收藏代码
  1. HibernateUtil.getSessionFactory().openSession();  

变为了 
Java代码   收藏代码
  1. HibernateUtil.getSessionFactory().getCurrentSession();  


难道是这句HibernateUtil.getSessionFactory().getCurrentSession();有猫腻? 
Checkout源码,跟进去看,果然: 
HibernateUtil.getSessionFactory().getCurrentSession()将Session交给一个CurrentSessionContext来处理,根据配置,使用的是ThreadLocalSessionContext这个东东。查看他的源码: 

Java代码   收藏代码
  1. public final Session currentSession() throws HibernateException {  
  2.         Session current = existingSession( factory );  
  3.         if (current == null) {  
  4.             current = buildOrObtainSession();  
  5.             // register a cleanup synch  
  6.             current.getTransaction().registerSynchronization( buildCleanupSynch() );  
  7.             // wrap the session in the transaction-protection proxy  
  8.             if ( needsWrapping( current ) ) {  
  9.                 current = wrap( current );//Warp Here????  
  10.             }  
  11.             // then bind it  
  12.             doBind( current, factory );  
  13.         }  
  14.         return current;  
  15.     }  


发现这里的Session已经是不纯洁了,已经成宋祖德嘴里的女明星了。被包了。看看被包的过程, 
Java代码   收藏代码
  1. protected Session wrap(Session session) {  
  2.         TransactionProtectionWrapper wrapper = new TransactionProtectionWrapper( session );  
  3.         Session wrapped = ( Session ) Proxy.newProxyInstance(  
  4.                 Session.class.getClassLoader(),  
  5.                 SESS_PROXY_INTERFACES,  
  6.                 wrapper  
  7.             );  
  8.         // yick!  need this for proper serialization/deserialization handling...  
  9.         wrapper.setWrapped( wrapped );  
  10.         return wrapped;  
  11.     }  

被包的很过分,直接换成代理了,看看代理人的嘴脸,这个代理人是TransactionProtectionWrapper 

看看他是用什么好东西包的: 
Java代码   收藏代码
  1. /** 
  2.          * {@inheritDoc} 
  3.          */  
  4.         public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {  
  5.             try {  
  6.                 // If close() is called, guarantee unbind()  
  7.                 if ( "close".equals( method.getName()) ) {  
  8.                     unbind( realSession.getSessionFactory() );  
  9.                 }  
  10.                 else if ( "toString".equals( method.getName() )  
  11.                          || "equals".equals( method.getName() )  
  12.                          || "hashCode".equals( method.getName() )  
  13.                          || "getStatistics".equals( method.getName() )  
  14.                          || "isOpen".equals( method.getName() ) ) {  
  15.                     // allow these to go through the the real session no matter what  
  16.                 }  
  17.                 else if ( !realSession.isOpen() ) {  
  18.                     // essentially, if the real session is closed allow any  
  19.                     // method call to pass through since the real session  
  20.                     // will complain by throwing an appropriate exception;  
  21.                     // NOTE that allowing close() above has the same basic effect,  
  22.                     //   but we capture that there simply to perform the unbind...  
  23.                 }  
  24.                 else if ( !realSession.getTransaction().isActive() ) {  
  25.                     // limit the methods available if no transaction is active  
  26.                     if ( "beginTransaction".equals( method.getName() )  
  27.                          || "getTransaction".equals( method.getName() )  
  28.                          || "isTransactionInProgress".equals( method.getName() )  
  29.                          || "setFlushMode".equals( method.getName() )  
  30.                          || "getSessionFactory".equals( method.getName() ) ) {  
  31.                         log.trace( "allowing method [" + method.getName() + "] in non-transacted context" );  
  32.                     }  
  33.                     else if ( "reconnect".equals( method.getName() )  
  34.                               || "disconnect".equals( method.getName() ) ) {  
  35.                         // allow these (deprecated) methods to pass through  
  36.                     }  
  37.                     else {  
  38.                         throw new HibernateException( method.getName() + " is not valid without active transaction" );  
  39.                     }  
  40.                 }  
  41.                 log.trace( "allowing proxied method [" + method.getName() + "] to proceed to real session" );  
  42.                 return method.invoke( realSession, args );  
  43.             }  
  44.             catch ( InvocationTargetException e ) {  
  45.                 if ( e.getTargetException() instanceof RuntimeException ) {  
  46.                     throw ( RuntimeException ) e.getTargetException();  
  47.                 }  
  48.                 else {  
  49.                     throw e;  
  50.                 }  
  51.             }  
  52.         }  


呵呵,几乎所有正常的操作都必须在transcation.isActive()条件下才能执行。我要用的get,load,save, saveOrUpdate,list都在此列。 

到此为止,算明白了。 寻到根了,Hibernate的理由是: 

org.hibernate.context.ThreadLocalSessionContext 

A CurrentSessionContext impl which scopes the notion of current session by the current thread of execution. Unlike the JTA counterpart, threads do not give us a nice hook to perform any type of cleanup making it questionable for this impl to actually generate Session instances. In the interest of usability, it was decided to have this default impl actually generate a session upon first request and then clean it up after the org.hibernate.Transaction associated with that session is committed/rolled-back. In order for ensuring that happens, the sessions generated here are unusable until after Session.beginTransaction() has been called. If close() is called on a session managed by this class, it will be automatically unbound. 

Additionally, the static bind and unbind methods are provided to allow application code to explicitly control opening and closing of these sessions. This, with some from of interception, is the preferred approach. It also allows easy framework integration and one possible approach for implementing long-sessions. 

The buildOrObtainSession, isAutoCloseEnabled, isAutoFlushEnabled, getConnectionReleaseMode, and buildCleanupSynch methods are all provided to allow easy subclassing (for long-running session scenarios, for example). 

Author: 

Steve Ebersole 

用别人的东西得小心,知道他背后干了什么很重要啊。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值