工具类代码如下:
package com.study.utils;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
// 常量名全大写,而该常量一般用于外部使用,内部使用建议定义变量获取
private static final String CONFIG_FILENAME = "/hibernate.cfg.xml";
private static String configFile = CONFIG_FILENAME;
private static Configuration cfg = new Configuration();// 创建Configuration对象
private static StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
private static SessionFactory factory;
//每个线程都有一个ThreadLocal类型的变量,可以用于存储表示本地线程中的数据
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
static {
try {
// 加载注册文件
cfg.configure(configFile);
// 创建SessionFactory
builder.applySettings(cfg.getProperties());
factory = cfg.buildSessionFactory(builder.build());
} catch (Exception e) {
System.out.println("SessionFactory error");
e.printStackTrace();
}
}
public static Session getSession() {
Session session = threadLocal.get();//获取ThreadLocal变量中的数据
if(session == null || !session.isOpen()){
if(factory == null){
buildSessionFactory();
}
// 打开session,预防factory到此处也并没有获取到(factory为null)
session = (factory != null) ? factory.openSession() : null;
//将session存入ThreadLocal变量
threadLocal.set(session);
}
return session;
}
public static void buildSessionFactory(){
try {
// 加载注册文件
cfg.configure(configFile);
// 创建SessionFactory
builder.applySettings(cfg.getProperties());
factory = cfg.buildSessionFactory(builder.build());
} catch (Exception e) {
System.out.println("SessionFactory error");
e.printStackTrace();
}
}
public static void closeSession() throws HibernateException{
Session session = threadLocal.get();//获取ThreadLocal变量中的数据
threadLocal.set(null);
if(session != null){
session.close();
}
}
}
创建工具类后,可以直接使用类名调用类中方法获取或者关闭Session:,如下:
获取Session:
Session session = HibernateUtil.getSession();
关闭Session:HibernateUtil.closeSession();