hibernate關于session的關閉實例解析
本文研究的主要是hibernate關于session的關閉,具體如下。
Student student = new Student();
student.setName("Jan");
student.setAge("22");
student.setAddress("廣東省肇慶市");
Session session =HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(student);
session.flush();
session.getTransaction().commit();
1、getCurrentSession()與openSession()的區(qū)別?
- 采用
getCurrentSession()創(chuàng)建的session會綁定到當前線程中,而采用openSession(),創(chuàng)建的session則不會 - 采用
getCurrentSession()創(chuàng)建的session在commit或rollback時會自動關閉,而采用openSession(),創(chuàng)建的session必須手動關閉
2、使用getCurrentSession()需要在hibernate.cfg.xml文件中加入如下配置:
- 如果使用的是本地事務(jdbc事務)
<property name="hibernate.current_session_context_class">thread</property>
- 如果使用的是全局事務(jta事務)
<property name="hibernate.current_session_context_class">jta</property>
openSession() 與 getCurrentSession() 有何不同和關聯(lián)呢?
在 SessionFactory 啟動的時候, Hibernate 會根據(jù)配置創(chuàng)建相應的 CurrentSessionContext ,在getCurrentSession() 被調(diào)用的時候,實際被執(zhí)行的方法是 CurrentSessionContext.currentSession() 。在currentSession() 執(zhí)行時,如果當前 Session 為空, currentSession 會調(diào)用 SessionFactory 的 openSession 。所以 getCurrentSession() 對于 Java EE 來說是更好的獲取 Session 的方法。
許多時候出現(xiàn)session is close();原因就是你在hibernate.cfg.xml里面設置了
<property name="hibernate.current_session_context_class">thread</property>
系統(tǒng)在commit();執(zhí)行完之后就關閉了session,這時候你手動再關閉session就當然提示錯誤了
總結
以上就是本文關于hibernate關于session的關閉實例解析的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
相關文章
Java通過SMS短信平臺實現(xiàn)發(fā)短信功能 含多語言
這篇文章主要為大家詳細介紹了Java通過SMS短信平臺實現(xiàn)發(fā)短信功能的相關資料,感興趣的小伙伴們可以參考一下2016-07-07
SpringBoot 項目中的圖片處理策略之本地存儲與路徑映射
在SpringBoot項目中,靜態(tài)資源存放在static目錄下,使得前端可以通過URL來訪問這些資源,我們就需要將文件系統(tǒng)的文件路徑與URL建立一個映射關系,把文件系統(tǒng)中的文件當成我們的靜態(tài)資源即可,本文給大家介紹SpringBoot本地存儲與路徑映射的相關知識,感興趣的朋友一起看看吧2023-12-12
使用JAXBContext輕松實現(xiàn)Java和xml的互相轉(zhuǎn)換方式
這篇文章主要介紹了依靠JAXBContext輕松實現(xiàn)Java和xml的互相轉(zhuǎn)換方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08

