SessionFactory.getCurrentSession與openSession的區別(轉)


SessionFactory.getCurrentSessionopenSession的區別
    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);
    }
 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM