Hibernate輔助類是用來負責啓動 Hibernate 和方便地操作org.hibernateSessionFactory
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
- public class HibernateUtil {
- private static final SessionFactory sessionFactory ;
- static{
- // Create the SessionFactory from hibernate.cfg.xml
- sessionFactory = new Configuration().configure().buildSessionFactory();
- }
- private static SessionFactory buildSessionFactory() {
- return sessionFactory;
- }
- public static SessionFactory getSessionFactory() {
- return sessionFactory;
- }
- }
只要你持有 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。