【译文】【学习】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