使用单例模式创建SessionFactory
public class HibernateUtil {
private static class SessionFactoryHolder{
private static SessionFactory SessionFactoryInstance;
private static StandardServiceRegistry registry;
static {
registry = new StandardServiceRegistryBuilder()
.configure()
.build();
try {
SessionFactoryInstance = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
}
catch (Exception e) {
StandardServiceRegistryBuilder.destroy( registry );
e.printStackTrace();
}
}
}
public static SessionFactory getSessionFactory(){
return SessionFactoryHolder.SessionFactoryInstance;
}
public static void closeSessionFactory(){
StandardServiceRegistryBuilder.destroy(SessionFactoryHolder.registry);
}
}
使用了静态内部类来实现懒加载、线程安全的SessionFactory创建
配置hibernate.cfg.xml实现单线程单Session
<property name="hibernate.current_session_context_class">thread</property>
使用Qurey测试
@SuppressWarnings("all")
public void b(){
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Query query = session.createQuery("FROM User");
query.getResultList().forEach(System.out::println);
HibernateUtil.closeSessionFactory();
}
User{name=‘c’, age=123, id=1}
User{name=‘d’, age=22, id=2}
五月 26, 2021 4:56:27 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/hb]
成功!