hibernate关于session的关闭问题

一、getCurrentSession()与openSession()的区别?session

* 采用getCurrentSession()建立的session会绑定到当前线程中,而采用openSession(),建立的session则不会spa

* 采用getCurrentSession()建立的session在commit或rollback时会自动关闭,而采用openSession(),建立的session必须手动关闭hibernate

二、使用getCurrentSession()须要在hibernate.cfg.xml文件中加入以下配置:线程

* 若是使用的是本地事务(jdbc事务)orm

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

* 若是使用的是全局事务(jta事务)事务

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


openSession() 与 getCurrentSession() 有何不一样和关联呢?it

在 SessionFactory 启动的时候, Hibernate 会根据配置建立相应的 CurrentSessionContext ,在getCurrentSession() 被调用的时候,实际被执行的方法是 CurrentSessionContext.currentSession() 。在currentSession() 执行时,若是当前 Session 为空, currentSession 会调用 SessionFactory 的 openSession 。因此 getCurrentSession() 对于 Java EE 来讲是更好的获取 Session 的方法。io


许多时候出现session is close();缘由就是你在hibernate.cfg.xml里面设置了

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

系统在commit();执行完以后就关闭了session,这时候你手动再关闭session就固然提示错误了

相关文章
相关标签/搜索