Hibernate的輔助類——HibernateUtil

Hibernate輔助類是用來負責啓動 Hibernate 和方便地操作org.hibernateSessionFactory

  1. import org.hibernate.SessionFactory;
  2. import org.hibernate.cfg.Configuration;
  3. public class HibernateUtil {
  4.     private static final SessionFactory sessionFactory ;
  5.     static{
  6.              // Create the SessionFactory from hibernate.cfg.xml
  7.            sessionFactory = new Configuration().configure().buildSessionFactory();
  8.      }
  9. private static SessionFactory buildSessionFactory() {
  10.                  return sessionFactory;
  11. }
  12.     public static SessionFactory getSessionFactory() {
  13.         return sessionFactory;
  14.     }
  15. }

       只要你持有 org.hibernate.SessionFactory,大可在任何時候、任何地點調用這個方法getCurrentSession() 方法

總會返回“當前的”工作單元session

Hibernate 提供三種跟蹤當前會話的方法。基於“線程”的方法不適合於產品環境,它僅用於 prototyping 和教學用途。後面將更詳細地討論會話跟蹤。

session的生命週期

     Session 在第一次被使用的時候,即第一次調用 getCurrentSession() 的時候,其生命週期就開始。然後它被 Hibernate 綁定到當前線程。當事務結束的時候,不管是提交還是回滾,Hibernate 會自動把org.hibernate.Session 從當前線程剝離,並且關閉它。假若你再次調用getCurrentSession(),你會得到一個新的org.hibernate.Session,並且開始一個新的工作單元。
        Hibernate org.hibernate.Session 的生命週期可以很靈活。絕對不要把應用程序設計成爲每一次數據庫操作都用一個新的 Hibernate org.hibernate.Session。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章