1、openSession 每一次獲得的是一個全新的session對象,而getCurrentSession獲得的是與當前線程綁定的session對象
package cn.kiwifly.view;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
import cn.kiwifly.util.MySessionFactory;
public class View {
public static void main(String[] args) {
Configuration configuration = new Configuration().configure();
SessionFactory sf = configuration.buildSessionFactory();
Session sessionOpen1 = sf.openSession();
Session sessionOpen2 = sf.openSession();
Session sessionThread1 = sf.getCurrentSession();
Session sessionThread2 = sf.getCurrentSession();
System.out.println(sessionOpen1.hashCode() + "<-------->" + sessionOpen2.hashCode());
System.out.println(sessionThread1.hashCode() + "<-------->" + sessionThread2.hashCode());
}
}
上面代碼輸出結果:
546579839<-------->1579795854
141106670<-------->141106670
2、openSession不需要配置,而getCurrentSession需要配置
1中代碼如果直接運行會報錯,要在hibernate.cfg.xml中加入如下代碼才行
<property name="current_session_context_class">thread</property>
這里我們是讓session與當前線程綁定,這里的線程范圍應該是一次瀏覽器的會話過程,也就是說打開網站和關閉瀏覽器這個時間段。
3、openSession需要手動關閉,而getCurrentSession系統自動關閉
openSession出來的session要通過:
session.close();而getSessionCurrent出來的session系統自動關閉,如果自己關閉會報錯
4、Session是線程不同步的,要保證線程安全就要使用getCurrentSession
