import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateFactoryUtil {
private final static SessionFactory sessionFactory;//一个应用一般只有一个SessioFactory,他的创建比较耗时。
static {
// 实例化配置对象 //读取hibernate.cfg.xml文件
Configuration configuration = new Configuration().configure();
// 实例化服务登记
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
// 获取Session工厂//根据配置文件信息产生SessionFactory对象
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
// 获取Session工厂
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}
或者
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
private static final SessionFactory sessionFactory=buildSessionFactory();
private static SessionFactory buildSessionFactory(){
Configuration configuration=new Configuration().configure();
ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
return configuration.buildSessionFactory(serviceRegistry);
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}