通常在應用程式裡面是透過 SessionFactory 來獲取一個 Session 物件
且 SessionFactory 保存了產生 SQL 的語句以及 Hibernate 運行時所有的映射關係
而在一般的情況下,整個應用程式只有一個 SessionFactory
所以通常會在應用程式初始的時候,執行 SessionFactory 的創建,以便後續各模組使用
例如以下程式表示
package org.control;
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
public class HibernateUtil {
private static final SessionFactory sessionFactory; //將 SessionFactory 宣告為靜態變數
static {
try {
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
//之後的任何程式或模組需要取的 session 時, 就可以共通的取用此 SessionFactory
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}