1. 程式人生 > >Hibernate中getCurrentSession()與openSession()的區別及應用

Hibernate中getCurrentSession()與openSession()的區別及應用

rop 綁定 cto 關閉 hiberna code pre thread 線程

獲取openSession和CurrentSession:
session=HibernateSessionFactory.getSession();
session=HibernateSessionFactory.getSessionFactory().getCurrentSession();

1、getCurrentSession()與openSession()的區別?

* 采用getCurrentSession()創建的session會綁定到當前線程中,而采用openSession()創建的session則不會
* 采用getCurrentSession()創建的session在commit或rollback時會自動關閉,而采用openSession()創建的
    session必須手動關閉

2、使用getCurrentSession()需要在hibernate.cfg.xml文件中加入如下配置

* 如果使用的是本地事務(jdbc事務)
<property name="hibernate.current_session_context_class">thread</property>
* 如果使用的是全局事務(jta事務)
<property name="hibernate.current_session_context_class">jta</property>

Hibernate中getCurrentSession()與openSession()的區別及應用