package util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateUtil {
private static SessionFactory sessionFactory;
// 存放Session的线程本地变量
private static ThreadLocal<Session> sessionThreadLocal = new ThreadLocal<Session>();
static {
try {
// 读取所有的配置文件
Configuration configuration = new Configuration();
configuration.configure();
// 注册配置文件服务
ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry();
// 构建SessionFactory用于创建Session
sessionFactory = configuration.buildSessionFactory(sr);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Session getSession() {
Session session = sessionThreadLocal.get();
if (session == null || !session.isOpen()) {
session = sessionFactory.openSession();
sessionThreadLocal.set(session);
}
return session;
}
public static void closeSession() {
Session session = sessionThreadLocal.get();
if (session != null) {
session.close();
sessionThreadLocal.remove();
}
}
}
HibernateUtil工具类回顾
最新推荐文章于 2018-09-27 20:27:06 发布