openSession 與 getCurrentSession的區別 openSession 與 getCurrentSession的區別

openSession 與 getCurrentSession的區別

 

一、openSession 每一次得到的是一個全新的session對象,而getCurrentSession得到的是與當前線程綁定的session對象html

 

[java]  view plain copy print ?
  1. package cn.kiwifly.view;  
  2.   
  3. import org.hibernate.SessionFactory;  
  4. import org.hibernate.cfg.Configuration;  
  5. import org.hibernate.classic.Session;  
  6.   
  7. import cn.kiwifly.util.MySessionFactory;  
  8.   
  9. public class View {  
  10.   
  11.     public static void main(String[] args) {  
  12.   
  13.         Configuration configuration = new Configuration().configure();  
  14.         SessionFactory sf = configuration.buildSessionFactory();  
  15.           
  16.         Session sessionOpen1 = sf.openSession();  
  17.         Session sessionOpen2 = sf.openSession();  
  18.           
  19.         Session sessionThread1 = sf.getCurrentSession();  
  20.         Session sessionThread2 = sf.getCurrentSession();  
  21.           
  22.         System.out.println(sessionOpen1.hashCode() + "<-------->" + sessionOpen2.hashCode());  
  23.         System.out.println(sessionThread1.hashCode() + "<-------->" + sessionThread2.hashCode());  
  24.           
  25.   
  26.     }  
  27.   
  28. }  

上面代碼輸出結果:java

546579839<-------->1579795854
141106670<-------->141106670瀏覽器

 

二、openSession不須要配置,而getCurrentSession須要配置安全

1中代碼若是直接運行會報錯,要在hibernate.cfg.xml中加入以下代碼才行session

 

[html]  view plain copy print ?
  1. <property name="current_session_context_class">thread</property>  

 

這裏咱們是讓session與當前線程綁定,這裏的線程範圍應該是一次瀏覽器的會話過程,也就是說打開網站和關閉瀏覽器這個時間段。post

 

三、openSession須要手動關閉,而getCurrentSession系統自動關閉網站

openSession出來的session要經過:ui

 

[java]  view plain copy print ?
  1. session.close();  
而getSessionCurrent出來的session系統自動關閉,若是本身關閉會報錯

 

 

四、Session是線程不一樣步的,要保證線程安全就要使用getCurrentSessionurl

相關文章
相關標籤/搜索