package com.andy.bbs.database.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 HibernateUtils {
private static ThreadLocal<Session> thread = new ThreadLocal<Session>();
private static Configuration configuration;
private static SessionFactory factory;
private static ServiceRegistry serviceRegistry;
static{
configuration = new Configuration().configure();
serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry();
factory = configuration.buildSessionFactory(serviceRegistry);
}
/**
* 获取session对象
* @return
*/
public static Session openSession() {
Session session = thread.get();
if(session == null) {
session = factory.openSession();
thread.set(session);
}
return session;
}
/**
* 关闭session
*/
public static void closeSession() {
Session session = thread.get();
if(session != null) {
session.close();
thread.set(null);
}
}
}
SSH之Hibernate读取配置文件工具类
最新推荐文章于 2019-05-17 15:27:09 发布