升级SessionFactory
将SessionFactory升级为单例模式
package com.q.utils;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtils {
private static SessionFactory sf;
//使用static仅在初次引用时生效一次,想要获取或者关闭对象使用提供的get/close方法即可
static {
try {
Configuration con = new Configuration().configure();
sf = con.buildSessionFactory();
} catch (Exception e) {
e.printStackTrace();
}
}
public static SessionFactory getSessionFactory() {
return sf;
}
public void closeSessionFactory() {
sf.close();
}
}
//Configuration conf = new Configuration().configure();//1、读取配置文件
//SessionFactory sf = conf.buildSessionFactory();// 2、创建SessionFactory
//Session session = sf.openSession();// 3、打开Session
//升级后的使用
SessionFactory sessionFactory = HibernateUtils.getSessionFactory();
Session session = sessionFactory.openSession();
配置hibernate.cfg.xml,引入新配置保证线程拥有唯一session实例
<!-- 2.4 保证线程有唯一session实例 -->
<property name="hibernate.current_session_context_class">thread</property>
测试查询
Query<User> query = session.createQuery("from User");
List<User> resultList = query.getResultList();
resultList.forEach(System.out::println);
结果
User{id=1, name='jdsfjdj', birthday=2021-05-13 11:02:04.0}
User{id=2, name='qsy', birthday=2021-05-14 08:47:01.0}
User{id=3, name='qsy', birthday=2021-05-14 08:50:10.0}
User{id=4, name='qsy', birthday=2021-05-14 09:02:00.0}
User{id=5, name='qsy', birthday=2021-05-14 09:06:27.0}
User{id=6, name='qsy', birthday=Fri May 14 09:06:54 CST 2021}