package com.sanqing.hibernate;
import javax.websocket.SessionException;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateSessionFactory {
private static String CONFIG_FILE_LOCATON = "/hibernate.cfg.xml";// 配置文件
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();// 定义ThreadLocal对象。
private static Configuration configuration = new Configuration();// 定义Configuration对象。
private static SessionFactory sessionFactory;// 定义SessionFactory对象。
private static String configFile = CONFIG_FILE_LOCATON;
static {
try {
configuration.configure(configFile);// 读取配置文件。
sessionFactory = configuration.buildSessionFactory();// 创建SessionFactory对象。
} catch (HibernateException e) {
System.err.println("%%% SessionFactory 对象创建失败 %%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();// 获得Session对象。
if (session == null || !session.isOpen()) {// 判断Session对象是否为空或者未打开。
if (sessionFactory == null) {// 如果没有创建SessionFactory对象
rebuildSessionFactroy();
}
// 如果SessionFactroy对象不为空,则调用其openSession方法创建。
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);// 在ThreadLocal中保存该session对象。
}
return session;
}
public static void rebuildSessionFactroy() {
try {
configuration.configure(configFile);// 配置文件
sessionFactory = configuration.buildSessionFactory();// 创建SessionFactory对象。
} catch (HibernateException e) {
System.err.println("%%% SessionFactory 对象创建失败 %%%");
e.printStackTrace();
}
}
public static void closeSession() throws SessionException {
Session session = (Session) threadLocal.get();// 获得Session对象。
threadLocal.set(null);// 将当前线程session对象从ThreadLocal对象中移除。
if (session != null) {
session.close();
}
}
public static SessionFactory getSessionFactory() {// 获得SessionFactroy
return sessionFactory;
}
public static void setConfigFile(String configFile) {// 设置新的配置文件
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
public static Configuration getConfigration() {// 获得Configration对象。
return configuration;
}
}