理解hibernate 已ThreadLocal管理session的機制。

在運用中我們獲得sesion 以

  Session session = sessionFactory.getCurrentSession();

在這裏如果我們採用thread方法對事務進行管理,即採用jdbc事務,那麼sessionFactory的底層是通過ThreadLocalSessionContext類來獲得session對象代碼如下:

 public org.hibernate.classic.Session getCurrentSession() throws HibernateException {
  if ( currentSessionContext == null ) {
   throw new HibernateException( "No CurrentSessionContext configured!" );
  }
  return currentSessionContext.currentSession();
 }

其中currentSessionContext類型爲ThreadLocalSessionContext

在ThreadLocalSessionContext的currentSession我們可見:

 public final Session currentSession() throws HibernateException {
  Session current = existingSession( factory );
  if (current == null) {
   current = buildOrObtainSession();
   // register a cleanup synch
   current.getTransaction().registerSynchronization( buildCleanupSynch() );
   // wrap the session in the transaction-protection proxy
   if ( needsWrapping( current ) ) {
    current = wrap( current );
   }
   // then bind it
   doBind( current, factory );//把當前的session和sessionFactory與當前線程關聯
  }
  return current;
 }

 

doBind()方法實現如下:

protected static Map sessionMap() {
  return ( Map ) context.get();
 }

 private static void doBind(org.hibernate.Session session, SessionFactory factory) {
  Map sessionMap = sessionMap();//sessionMap方法爲獲得與當前線程綁定的值,返回爲Map類型
  if ( sessionMap == null ) {
   sessionMap = new HashMap();
   context.set( sessionMap );
  }
  sessionMap.put( factory, session );//把factory和session放入與當前線程綁定的map中,這樣,就形成了當前線程與session的傳遞關聯。
 }

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章