getCurrentSession()与openSession()的区别?
1、getCurrentSession()與openSession()的區(qū)別?
- 采用getCurrentSession()創(chuàng)建的session會綁定到當前線程中,而采用openSession(),創(chuàng)建的session則不會
- 采用getCurrentSession()創(chuàng)建的session在commit或rollback時會自動關(guān)閉,而采用openSession(),創(chuàng)建的session必須手動關(guān)閉
2、使用getCurrentSession()需要在hibernate.cfg.xml文件中加入如下配置:
- 如果使用的是本地事務(wù)(jdbc事務(wù))
- 如果使用的是全局事務(wù)(jta事務(wù))
openSession() 與 getCurrentSession() 有何不同和關(guān)聯(lián)呢?
在 SessionFactory 啟動的時候, Hibernate 會根據(jù)配置創(chuàng)建相應(yī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里面設(shè)置了
<property name="hibernate.current_session_context_class">thread</property>系統(tǒng)在commit();執(zhí)行完之后就關(guān)閉了session,這時候你手動再關(guān)閉session就當然提示錯誤了
總結(jié)
以上是生活随笔為你收集整理的getCurrentSession()与openSession()的区别?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Hibernate实现limit查询报错
- 下一篇: 图解 Hibernate,session