【譯文】【學習】Hibernate openSession和getCurrentSession的區別


【目標讀者】

  本教程為那些需要理解Hibernate框架以及使用Hibernate框架應用的java程序員而設計。

【前置條件】

  你需要先懂得java語言以及sql基本知識。

【教程目錄】

Introduction to hibernate framework

Hibernate hello world example in eclipse 

Difference between openSession and getCurrentSession 

Hibernate one to one mapping example 

Hibernate one to many mapping example 

Hibernate many to many mapping example 

Hibernate inheritance:Table per class hierarchy 

Hibernate inheritance:table per subclass 

Hibernate inheritance:Table per concrete class 

Difference between openSession and getCurrentSession 

Difference between get and load 

Spring MVC Hibernate MySQL CRUD example 

Spring Rest hibernate example

 

【Hibernate獲取Session的方法】

  Hibernate 有兩種方法可以創建或者獲取session,SessionFactory 類有倆種方法創建session。

    openSession

    getCurrentSession

 

【區別】

  openSession: 當調用SessionFactory的openSession方法時,它總是創建一個完全全新的session給你。你需要顯示的刷新並且關閉session對象。

         因為session對象不是線程安全的,在多線程環境中你需要為每一個請求創建一個session對象(例如web應用的每一個請求)。

  getCurrentSession: 當調用SessionFactory的getCurrentSession方法時,它會返回Hibernate上下文中的Session,並且有hibernate管理。它綁定到事物范圍。

            當調用SessionFactory的getCurrentSession方法時,如果不存在他會創建一個新的Session對象,如果在當前的hibernate上下文中存在,則返回同樣的Session對象。

            它會自動地flush和close,當事物結束的時候,所以無需多余處理。如果你在單線程環境下使用hibernate,你應該用getCurrentSession,它的性能比較好。

            如果你要使用getCurrentSession,你需要配置如下:

<session-factory>  
<!--  Put other elements here -->  
<property name="hibernate.current_session_context_class">  
          thread  
</property>  
</session-factory>  

          如果沒有這個配置會報錯:No CurrentSessionContext configured! 

 

【總結】

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM