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(); } } }

发布了62 篇原创文章 · 获赞 36 · 访问量 15万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章