![](/img/trans.png)
[英]Hibernate: sessionFactory.openSession() VS sessionFactory.getCurrentSession()
[英]Difference b/w Hibernate's Sessionfactory.getCurrentSession() and SessionFactory.openSession()
我對兩者有點困惑。 As per I know both returns hibernate session, SessionFactory.getCurrentSession()
returns a contextual session based on the property <property name="current_session_context_class">
which is set in hibernate.cfg.xml Shouldn't we always go with this approach?
SessionFactory.openSession()
增加了什么附加值?
每當第一次調用sf.getCurrentSession()
時,都會打開一個 session。 如果不存在,這將創建一個全新的 session,如果已經存在,則使用現有的。
在 Tomcat 中,這將 session 與使用底層ThreadLocal
object 創建的線程相關聯。但是由於 Tomcat 使用線程池,因此請求完全有可能接收到一個已經與它關聯的 session 的線程,從而引入了不均勻的可能性創建一個全新的 session。另一件事是您使用sf.getCurrentSession()
獲得的 Session 會自動刷新並關閉。
另一方面,方法sf.openSession()
創建一個新的 session 但不嘗試將其與線程相關聯。 但請記住sf.openSession()
引入了另一個障礙,因為它希望用戶自己處理會話的關閉和刷新,而不是讓 Hibernate 自動為我們完成。
sf.getCurrentSession()
通常就足夠了。 sf.openSession()
提供並促進對 session 的存儲和管理位置進行更高級別的管理。 這當然是一個高級選項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.