package com.newer;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
/**
* HibernateSessionFactory 工具類 <br/>
* 此類用于獲取 sessionFactory、session等
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; //位置classPath里面:
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
//private static Configuration configuration = new Configuration(); //XML配置時使用
private static Configuration configuration = new AnnotationConfiguration(); //@注解配置時使用
static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* 構(gòu)造方法
*/
private HibernateSessionFactory() {
}
/**
* 獲取Session的方法 <br/>
* session使用完后應(yīng) close()釋放掉<br/>
* 因為每個session 都會帶上一個數(shù)據(jù)庫連接
* @return
*/
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();
}
}
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* 獲取sessionFactory的方法
* @return
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* 清空 sessionFactory 的方法
* @return
*/
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
/**
* 獲取 configuration 的方法
* @return
*/
public static Configuration getConfiguration() {
return configuration;
}
}
聯(lián)系客服