Hibernate实用类创建SessionFactory

//通过Configuration的对象调用configure()方法加载Hibernate配置文件创建SessionFactory 由于SessionFactory 的创建费时,所以放在static下面
//让他只初始化一次最后返回一个SessionFactory 。

//下面是两种模式的SessionFactory:一种是通过映射文件,一种是通过注解。
public class HibernateUtilMapping {
private static final SessionFactory sessionFactory =buildSessionFactory();

private static SessionFactory buildSessionFactory(){
try {
return new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// TODO Auto-generated catch block
System.err.println("Initial SessionFactory creationfailed."+ex);
throw new ExceptionInInitializerEr
ror(ex); } } public static SessionFactory getSessionFactory(){ return sessionFactory; } public static void closeSession(Session session){ if(session.isOpen()){ session.close(); } } } public class HibernateUtilAnnotation { private static final SessionFactory sessionFactory =buildSessionFactory(); private static SessionFactory buildSessionFactory(){ try { return newAnnotationConfiguration().configure().buildSessionFactory(); } catch (Throwable ex) { // TODO Auto-generated catch block System.err.println("Initial SessionFactory creationfailed."+ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory(){ return sessionFactory; } public static void closeSession(Session session){ if(session.isOpen()){ session.close(); } } }

你可能感兴趣的:(Hibernate)