hibernate创建sessionFactory的不同方式

在使用Hibernate时,不同的版本对应的SessionFactory的创建方式也不同

Hibernate 3.x

SessionFactory sessionFactory = null;

//1). 创建 Configuration 对象: 对应 hibernate 的基本配置信息和 对象关系映射信息
Configuration configuration =  new Configuration().configure();

sessionFactory = configuration.buildSessionFactory();

Hibernate 4.x

SessionFactory sessionFactory = null;

//1). 创建 Configuration 对象: 对应 hibernate 的基本配置信息和 对象关系映射信息
Configuration configuration =  new Configuration().configure();

//2). 创建一个 ServiceRegistry 对象: hibernate 4.x 新添加的对象
//hibernate 的任何配置和服务都需要在该对象中注册后才能有效.
ServiceRegistry serviceRegistry = 
                        new ServiceRegistryBuilder().applySettings(configuration.getProperties())
.buildServiceRegistry();

//3).
sessionFactory = configuration.buildSessionFactory(serviceRegistry);

Hibernate 5.x

protected void setUp() {

    final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure().build();
    try {
        sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
    }
    catch (Exception e) {
        // The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
        // so destroy it manually.
        StandardServiceRegistryBuilder.destroy( registry );
    }
}

你可能感兴趣的:(Hibernate)