Hibernate 初始化:獲取SessionFactory的各種方式
阿新 • • 發佈:2019-02-19
其實網路上已經存在很多關於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
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
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 );
}
}