Hibernate 初始化:获取SessionFactory的各种方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lmmzsn/article/details/78213958

其实网络上已经存在很多关于Hibernate初始化的文章了。但是,随着Hibernate版本不断升级,有些初始化的方式已经悄悄的变成了坑。

今天就遇到了下面的坑(基于Hibernate 5.2.10):

Configuration cfg = new Configuration().configure("hibernate/hibernate.cfg.xml");
ServiceRegistry sr= new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
SessionFactory sf = cfg.buildSessionFactory(sr);


通过这种方式,在Session保存对象时会发生类似下面这种错误:

 org.hibernate.MappingException: Unknown entity: test.hibernate.StudentModel

首先声明,我的配置是没问题的,在hibernate.cfg.xml也引入了StudentModel的Mapping文件。

遇到这个问题后,我首先想到的是要找到错误发生的根源。

然后我就开始分析Hibernate源码,但是,根据问题发生的地方往上追溯了半天也没找到根本原因。于是就想看看网上有没有发生过类似问题的。

在网络上搜索,关键词很重要。

如果直接搜索: 【org.hibernate.MappingException: Unknown entity:】的话,出现的解决办法都是告诉你要正确配置文件或正确引入类。很显然这解决不了我的问题。

如果搜索:【Hibernate 5 mapping找不到】的话,正确的解决办法就出现了。其实就是按照Hibernate官网介绍的方式进行初始化。


下面整理了Hibernate官网介绍的针对各个版本的初始化方式,不过没有找到类似上面提到的那个坑的方式,不知道谁发明的。

注:其实在Hibernate 5.xxx里使用以前的初始化方式还是可以的,这说明Hibernate做了很好的向后兼容。


Hibernate 4.2/4.3

参考:http://docs.jboss.org/hibernate/orm/4.3/quickstart/en-US/html_single/

protected void setUp() throws Exception {
    // A SessionFactory is set up once for an application
    sessionFactory = new Configuration()
            .configure() // configures settings from hibernate.cfg.xml
            .buildSessionFactory();
}


Hibernate 5.0/5.1/5.2

参考:http://docs.jboss.org/hibernate/orm/5.2/quickstart/html_single/

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



猜你喜欢

转载自blog.csdn.net/lmmzsn/article/details/78213958