1、getCurrentSession()与openSession()的区别
web
1、getCurrentSession () 使用当前的session
openSession() 从新创建一个新的sessionsession
2、采用getCurrentSession()建立的session会绑定到当前线程中,spa
而采用openSession()建立的session则不会
3、 采用getCurrentSession()建立的session在commit或rollback后,会自 动关闭,而采用openSession()建立的session必须手动关闭
4、使用getCurrentSession()须要在hibernate.cfg.xml文件中加入以下配置:
(1) 若是使用的是本地事务(jdbc事务)
<property name="hibernate.current_session_context_class">thread</property>
(2)若是使用的是全局事务(jta事务)
<property name="hibernate.current_session_context_class">jta</property>hibernate
2、openSession() 与 getCurrentSession() 有何不一样和关联呢?线程
在 SessionFactory 启动的时候, Hibernate 会根据配置建立相应的 CurrentSessionContext ,在 getCurrentSession() 被调用的时候,实际被执行的方法是 CurrentSessionContext.currentSession() 。在 currentSession() 执行时,若是当前 Session 为空, currentSession 会调用 SessionFactory 的 openSession 。因此 getCurrentSession() 对于 Java EE 来讲是更好的获取 Session 的方法。在一个应用程序中,若是DAO 层使用Spring 的hibernate 模板,经过Spring 来控制session 的生命周期,则首选getCurrentSession ()。orm