package com.hibernate.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
/**
* 可重用
* @author Aimer
*
*/
public class HibernateUtil {
private static SessionFactory sessionFactory;
/**
* 静态初始化
*/
static {
//1.创建ServiceRegistry对象
StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure().build();//读取hibernate.cfg.xml
try {
//2.创建SessionFactory对象
sessionFactory = new MetadataSources(registry).buildMetadata()
.buildSessionFactory();
} catch (Exception e) {
e.printStackTrace();
//手动释放StandardServiceRegistry对象
StandardServiceRegistryBuilder.destroy(registry);
}
}
/**
* 创建Session对象:程序与数据库的一次会话
*/
public static Session OpenSession() {
return sessionFactory.openSession();
}
/**
* 关闭SessionFactory
*/
public static void closeSessionFactory() {
sessionFactory.close();
}
}
12-12
689
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
04-30