HibernateSessionFactory 採用經典單例模式,透過 ThreadLocal 管理每執行緒的 Session,核心欄位皆為 private static:
CONFIG_FILE_LOCATION:Hibernate 設定檔路徑threadLocal:儲存當前執行緒的 Sessioncfg:Configuration 單例sessionFactory:SessionFactory 單例public static Session currentSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null) {
if (sessionFactory == null) {
try {
cfg.configure(CONFIG_FILE_LOCATION);
sessionFactory = cfg.buildSessionFactory();
} catch (Exception e) { /* 錯誤處理 */ }
}
session = sessionFactory.openSession();
threadLocal.set(session);
}
return session;
}
雙重檢查鎖定模式確保 SessionFactory 僅建立一次,並綁定到當前執行緒。
private HibernateSessionFactory() {}
防止外部直接實例化,強制使用靜態方法 currentSession()、closeSession() 管理 Session 生命週期。
本文來自編程入門網:原文連結