天天看點

hibernate 中Sessionfactory的getCurrentSession與openSession的差別

   Configuration cfg = new Configuration();  // 獲得配置資訊對象

   SessionFactory sf = cfg.configure().buildSessionFactory(); //解析并建立Session工廠

  1. Session session = sf.getCurrentSession(); // 獲得Session

  2. Session session = sf.openSession(); // 打開Session

對于上述的兩個方法,有以下差別:

  1. openSession 從字面上可以看得出來,是打開一個新的session對象,而且每次使用都是打開一個新的session,假如連續使用多次,則獲得的session不是同一個對象,并且使用完需要調用close方法關閉session。

  2. getCurrentSession ,從字面上可以看得出來,是擷取目前上下文一個session對象,當第一次使用此方法時,會自動産生一個session對象,并且連續使用多次時,得到的session都是同一個對象,這就是與openSession的差別之一,簡單而言,getCurrentSession 就是:如果有已經使用的,用舊的,如果沒有,建新的。

注意:在實際開發中,往往使用getCurrentSession多,因為一般是處理同一個事務(即是使用一個資料庫的情況),是以在一般情況下比較少使用openSession或者說openSession是比較老舊的一套接口了;

對于getCurrentSession 來說,有以下一些特點:

1.用途,界定事務邊界

2.事務送出會自動close,不需要像openSession一樣自己調用close方法關閉session

3.上下文配置(即在hibernate.cfg.xml)中,需要配置:

    <property name="current_session_context_class">thread</property>

(需要注意,這裡的current_session_context_class屬性有幾個屬性值:jta 、 thread 常用 , custom、managed 少用  )

a).thread使用connection 單資料庫連接配接管理事務

b).jta (java  transaction api) Java 分布式事務管理(多資料庫通路),jta 由中間件提供(JBoss WebLogic 等,但是tomcat 不支援)

摘自:

http://blog.sina.com.cn/s/blog_6ac4c6cb010182zg.html

繼續閱讀