HibernateUtil

时间:2022-11-09 22:00:00
 package com.ssh.util;

 import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.tool.hbm2ddl.SchemaExport; public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() {
try { //Hibernate 4.x 时代
Configuration cfg = new Configuration();
cfg.configure(); // SchemaExport se = new SchemaExport(cfg);
// se.create(true, true); ServiceRegistry sr =
new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties())
.build(); SessionFactory factory = cfg.buildSessionFactory(sr); return factory;
// Create the SessionFactory from hibernate.cfg.xml
// return new Configuration().configure().buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
} public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}