Skip to content

Instantly share code, notes, and snippets.

@fishLite
Last active September 8, 2017 03:57
Show Gist options
  • Save fishLite/b312a0c57c266a8bdbd502996f34b892 to your computer and use it in GitHub Desktop.
Save fishLite/b312a0c57c266a8bdbd502996f34b892 to your computer and use it in GitHub Desktop.
HibernateSssionFactory 辅助工具类,既负责Hibernate的启动,也负责完成存储和访问SessionFactory的工作
package cn.it.shop.util;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/*Hibernate:辅助工具类,既负责Hibernate的启动,也负责完成存储和访问SessionFactory的工作。
* 使用Hibernate类来处理java应用程序中的Hibernate的启动是一种常见的模式
*/
public class HibernateSessionFactory {
private static SessionFactory sessionfactory;
// 创建线程局部变量threadLocal,用来保存Hibernate中的Session
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
// 使用静态代码块来初始化Hibernate
static {
try {
Configuration cfg = new Configuration().configure("/hibernate.cfg.xml");// 读取配置文件hibernate.cfg.xml
sessionfactory = cfg.buildSessionFactory(); // 创建SessionFactory
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
// 获得SessionFactory的实例
public static SessionFactory getSessionFactory() {
return sessionfactory;
}
// 获得ThreadLocal对象管理的Session实例
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
// 通过sessionfactory创建session
if (sessionfactory == null) {
rebuildSessionFactory();
}
session = (sessionfactory != null) ? sessionfactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
// 关闭Session实例
public static void closeSession() throws HibernateException {
Session session = threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
// 关闭缓存和连接池
public static void shutdown() {
sessionfactory = getSessionFactory();
if (sessionfactory != null) {
sessionfactory.close();
}
}
// 重建SessionFactory
private static void rebuildSessionFactory() {
try {
Configuration cfg = new Configuration()
.configure("/HibernateConf/hibernate.cfg.xml");
sessionfactory = cfg.buildSessionFactory();
} catch (Exception e) {
System.out.println("SessionFactory build error");
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment