getCurrentSession與openSession的區別

來源:互聯網
上載者:User

 

1. 如果使用的是getCurrentSession來建立session的話,在commit後,session就自動被關閉了,也就是不用再session.close()了。但是如果使用的是openSession方法建立的session的話,那麼必須顯示的關閉session,也就是調用session.close()方法。這樣commit後,session並沒有關閉
 

2. getCurrentSession的使用可以參見hibernate\hibernate-3.2\doc\tutorial\src項目

3. 使用SessionFactory.getCurrentSession()需要在hibernate.cfg.xml中如下配置:
 

 

* 如果採用jdbc獨立引用程式配置如下:
<property name="hibernate.current_session_context_class">thread</property>
* 如果採用了JTA事務配置如下  
<property name="hibernate.current_session_context_class">jta</property>

 

 

利於ThreadLocal模式管理Session
  

早在Java1.2推出之時,Java平台中就引入了一個新的支援:java.lang.ThreadLocal,給我們在編寫多線程程式
時提供了一種新的選擇。ThreadLocal是什麼呢?其實ThreadLocal並非是一個線程的本地實現版本,它並不是一

個Thread,
  

而是thread local variable(線程局部變數)。也許把它命名為ThreadLocalVar更加合適。線程局部變數(ThreadLocal)
  

其實的功用非常簡單,就是為每一個使用某變數的線程都提供一個該變數值的副本,是每一個線程都可以獨立地改變自己的副本,
  

而不會和其它線程的副本衝突。從線程的角度看,就好像每一個線程都完全擁有一個該變數。
  

ThreadLocal是如何做到為每一個線程維護變數的副本的呢?其實實現的思路很簡單,在ThreadLocal類中有一個Map,用於儲存每一個線程的變數的副本。比如下面的樣本實現(為了簡單,沒有考慮集合的泛型):

public  class  HibernateUtil 

{
 
public static final ThreadLocal session =new ThreadLocal();
 
public  static  final  SessionFactory  sessionFactory;

static 

{
      try 

      {
        sessionFactory  =  new  Configuration().configure().buildSessionFactory();
      }

      catch (Throwable  ex)

      {
           throw  new  ExceptionInInitializerError(ex);
      }    
 }
 
    

public  static  Session  currentSession()  throws  HibernateException 

{
        Session  s  =  session.get();
        if(s  ==  null) 

        {
          s  =  sessionFactory.openSession();
          session.set(s);
        }
         return  s;
       }

}

 

public  static  void  closeSession()  throws  HibernateException 

{
        Session  s  =  session.get();
        if(s  !=  null) 

        {
            s.close();
        }
        session.set(null);
    }
 }

 

原帖地址:http://blog.sina.com.cn/s/blog_606b1aab0100diaa.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.