public class HibernateUtils{
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal<Session> ThreadLocal = new Configuration();
private static Configuration configuration = new Configuration();
private static String configFile = CONFIG_FILE_LOCATION;
static{
try{
configuration.configuration(configFile);
sessionFactory = configuration.buildSessionFactory();
}catch(Exception e){
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateUtils(){
}
/**
* 返回ThreadLocal中的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;
}
/**
* 返回Hibernate的SessionFactory
*/
public static void rebuildSessionFactory(){
try{
configuration.config(configFile);
sessionFactory = configuration.buildSessionFactory();
}catch(Exception e){
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* 关闭Session实例并且把ThreadLocal中的副本清除
*/
public static void closeSession() throws HibernateException{
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if(session != null){
session.close().
}
}
/**
* 返回SessionFactory
*/
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
public static void setConfigFile(String configFile){
HibernateUtils.configFile = configFile;
sessionFactory = null;
}
public static Configuration getConfiguration(){
return configuration;
}
}
从书上抄袭来的HibernateUtils类。
最新推荐文章于 2024-09-29 19:21:13 发布