hibernate5 创建SessionFactory 总结三种方法均可(亲测)

第一种:与hibernate4.0之前相同,只需要一句

SessionFactory factory = cfg.buildSessionFactory();

第二种:稍微麻烦

StandardServiceRegistry standardServiceRegistry = new StandardServiceRegistryBuilder().configure().build();
       Metadata metadata = new MetadataSources(standardServiceRegistry).getMetadataBuilder()
               .applyImplicitNamingStrategy(ImplicitNamingStrategyComponentPathImpl.INSTANCE).build();
       SessionFactory factory = metadata.getSessionFactoryBuilder().build();

第三种:这种在官网下载的hibernate5中有 user-guide文档说明,所以跟着官方写应该不会出错

此为文档目录:\hibernate-release-5.4.4.Final\documentation\userguide\html_single\Hibernate_User_Guide.html

protected void setUp() throws Exception {
	// A SessionFactory is set up once for an application!
	final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
			.configure() // configures settings from hibernate.cfg.xml
			.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 );
	}
}

以下为上方的精简版:

ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
        SessionFactory factory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();

最后创建session:Session session = factory.openSession();

三种方法均可实现创建SessionFactory.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值