Hibernate中的GetCurrentSession()方法

从3.0.1版本开 始,Hibernate增加了SessionFactory.getCurrentSession()方法。

采用getCurrentSession()创建的session在commit或rollback时会自动关闭,如果commit()之后再关闭,就会报session已经关闭的错误;但是如果不commit()而执行关闭,虽然不会报什么错误,但是这时观察数据库添加数据是没有成功的,而openSession必须手动关闭。

在一个应用程序中,如果DAO 层使用Spring来控制session 的生命周期,则首选getCurrentSession()。

在 SessionFactory 启动的时候,Hibernate 会根据配置创建相应的 CurrentSessionContext,在 getCurrentSession()被调用的时候,实际被执行的方法是 CurrentSessionContext.currentSession()。在 currentSession() 执行时,如果当前Session 为空,currentSession 会调用 SessionFactory的openSession。

getCurrentSession配置:

如果使用的是本地事务(jdbc事务)

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

 

如果使用的是全局事务(jta事务)

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

 

posted @ 2016-10-20 21:00  Timesyys  阅读(1884)  评论(0编辑  收藏  举报