1. 程式人生 > >getCurrentSession 與 openSession區別

getCurrentSession 與 openSession區別

通過 ring log ttr 調用 session cfg.xml 重新 action

getCurrentSession () 使用當前的session
openSession()重新建立一個新的session

使用SessionFactory.getCurrentSession()需要在hibernate.cfg.xml中如下配置:

* 如果采用jdbc獨立引用程序配置如下:
<property name="hibernate.current_session_context_class">thread</property>
* 如果采用了JTA事務配置如下 
<property name="hibernate.current_session_context_class">jta</property>
Session session = HibernateUnit.getSessionFactory().getCurrentSession();
session.beginTransaction();
....
session.getTransaction().commit();

使用openSession()不需要配置如上的hibernate.cfg.xml配置

代碼如下:

        Session session=HibernateUtils.openSession();
        Transaction transaction = session.beginTransaction();
        .......
        transaction.commit();
        session.close();

j

結論:在一個應用程序中,如果DAO 層使用Spring 的hibernate 模板,通過Spring 來控制session 的生命周期,則首選getCurrentSession ()

   如果使用的是getCurrentSession來創建session的話,在commit後,session就自動被關閉了,不用再session.close()了。

    但是如果使用的是openSession方法創建的session的話,那麽必須顯示的關閉session,也就是調用session.close()方法。這樣commit後,session並沒有關閉

    getcurrentSession()的Session 在第一次被使用的時候,即第一次調用getCurrentSession()的時候,其生命周期就開始。

    然後她被Hibernate綁定到當前線程。當事物結束的時候,不管是提交還是回滾,Hibernate會自動把Session從當前線程剝離,並且關閉。

    若在次調用 getCurrentSession(),會得到一個新的Session,並且開始一個新的工作單元。

getCurrentSession 與 openSession區別