[Hibernate]关于Hibernate buildsessionfactory()过时处理

原文地址:http://liuhd2010.iteye.com/blog/2042299

Hibernate创建SessionFactory在Hibernate3中和Hibernate4中写法是不一样的,

在Hibernate3中写法:

static SessionFactory sessionFactroy;  
static {  
    try{  
        Configuration config = new Configuration().configure();  
        sessionFactory = config.buildSessionFactory();  
    }catch(Exception e){  
        e.printStackTrace();  
    }      
}  

在Hibernate4中写法:

private static SessionFactory sessionFactory;  
private static ServiceRegistry serviceRegistry;  
public static SessionFactory createSessionFactory()throws HibernateException{  
    Configuration configuration = newConfiguration();  
    configuration.configure();  
    serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();          
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);  
    return sessionFactory;  
} 

这里给出一个创建SessionFactory工具类,在工程中加入该类后可直接引用:

import org.hibernate.Session;  
import org.hibernate.SessionFactory;  
import org.hibernate.cfg.Configuration;  
import org.hibernate.service.ServiceRegistry;  
import org.hibernate.service.ServiceRegistryBuilder;  
  
public class HibernateUtils{  
    private static SessionFactory factory;  
        static{  
        Configuration cfg = new Configuration().configure();  
        ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(  
                cfg.getProperties()).buildServiceRegistry();  
        factory = cfg.buildSessionFactory(sr);  
    }  
  
    public static SessionFactory getSessionFactory(){  
        return factory;  
    }  
  
    public static Session getSession(){  
        return factory.openSession();  
    }  
  
    public static void closeSession(Session session){  
        if (session != null){  
            if (session.isOpen()){  
                session.close();  
            }  
        }  
    }  
}  





你可能感兴趣的:([Hibernate]关于Hibernate buildsessionfactory()过时处理)