package org.hibernate.util;
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();
//在4.0以后的版本,此方法已经过时
private static SessionFactory buildSessionFactory1() {
return new Configuration().configure().buildSessionFactory();
}
private static SessionFactory buildSessionFactory() {
try {
Configuration configure= new Configuration().configure();
ServiceRegistry serviceRegistry=
new StandardServiceRegistryBuilder()
.applySettings(configure.getProperties())
.build();
return configure.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
private static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static org.hibernate.Session getSession() {
return sessionFactory.openSession();
}
}