博爲峯小博老師:數據庫
Session對象是Hibernate中數據庫持久化操做的核心,它負責Hibernate全部的持久化操做,經過它開發人員能夠實現數據庫基本的增、刪、查、改的操做。而Session對象又是經過SessionFactory對象獲取的,能夠經過Configuration對象建立SessionFactory,關健代碼以下:session
Configuration對象會加載Hibernate的基本配置信息,若是沒有在configure()方法中指定加載配置XML文檔的路徑信息,Configuration對象會默認加載項目classpath根目錄下的hibernate.cfg.xml文件。ui
建立HibernateUtil類,用於實現對Hibernate的初始化。代碼以下:spa
public class HibernateUtil {hibernate
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";code
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();xml
private static Configuration configuration = new Configuration(); 對象
private static org.hibernate.SessionFactory sessionFactory; //SessionFactory對象blog
private static String configFile = CONFIG_FILE_LOCATION;ip
static {
try {
configuration.configure(configFile);//加載Hibernate配置文件
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* 獲取Session
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
*重建會話工廠
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* 獲取SessionFactory對象
*/
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
/**
* 關閉Session
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
}