日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

getCurrentSession()与openSession()的区别?

發布時間:2025/3/21 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 getCurrentSession()与openSession()的区别? 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1、getCurrentSession()與openSession()的區別?

  • 采用getCurrentSession()創建的session會綁定到當前線程中,而采用openSession(),創建的session則不會
  • 采用getCurrentSession()創建的session在commit或rollback時會自動關閉,而采用openSession(),創建的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() 有何不同和關聯呢?

在 SessionFactory 啟動的時候, Hibernate 會根據配置創建相應的 CurrentSessionContext ,在getCurrentSession() 被調用的時候,實際被執行的方法是 CurrentSessionContext.currentSession() 。在currentSession() 執行時,如果當前 Session 為空, currentSession 會調用 SessionFactory 的 openSession 。所以 getCurrentSession() 對于 Java EE 來說是更好的獲取 Session 的方法。

許多時候出現session is close();原因就是你在hibernate.cfg.xml里面設置了

<property name="hibernate.current_session_context_class">thread</property>

系統在commit();執行完之后就關閉了session,這時候你手動再關閉session就當然提示錯誤了

總結

以上是生活随笔為你收集整理的getCurrentSession()与openSession()的区别?的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。