hibernate學習4_openSession()與getCurrentSession()區別

來源:互聯網
上載者:User

標籤:

hibernate讀取設定檔建立sessionBuildFactory後可以通過如下兩種方式建立session

(1)openSession()

     此方法每次會產生一個新session

  如下測試後返回false,說明兩次產生的session不是同一個session

    @Test    public  void testOpenSession(){        Session session1 = sf.openSession();        Session session2 = sf.openSession();        System.out.println(session1==session2);    }

注意:每次opensession執行後需要手動關閉session

 

(2) getCurrentSession()

 此方法從上下文中擷取session,如果上下文中沒有,則自動產生一個session

 如下執行後,前一個返回true,後一個返回false

        @Test    public void testGetCurSession(){        Session session1 = sf.getCurrentSession();        Session session2 = sf.openSession();        Session session3 = sf.getCurrentSession();        System.out.println(session1==session2);        System.out.println(session3==session2);

 

如下測試後返回true,說明兩次產生的session不是同一個session

常見的上下文有thread和JTA,在hibernate.cfg.xml中配置

         <!-- Enable Hibernate‘s automatic session context management -->        <property name="current_session_context_class">thread</property>

 thread :即從當前線程中擷取。

    JTA  : 管理分散式資料庫

 

實際在應用中,一般用getCurrentSession()來界定事務邊界,openSession()產生多個session不在一個事務中,難以界定。

除此外,getCurrentSession()中session提交後會自動關閉,手動關閉會報錯

        而openSession()必須手動關閉。

hibernate學習4_openSession()與getCurrentSession()區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.