Hibernate兩種得到sessionFactory方式的區別

     Hibernate 能夠經過sessionFactory.openSession()和sessionFactory.getCurrentSession()來得到session,下面來淺說一下二者區別。數據庫


【sessionFactory.openSession()】
     經過session工廠sessionFactory.openSession()方法來得到一個session,每次都建立一個新的session出來,而且每次Hibernate都會打開數據庫和應用程序的鏈接。session


【sessionFactory.getCurrentSession()】
    經過session工廠的sessionFactory.getCurrentSession()方法得到session,而且與當前線程ThreadLocal綁定,但要在Hibernate中配置屬性參數 current_session_context_class ,而且value設置爲thread。不然通常會報沒有配置當前線程的錯誤。經過此方式得到session有4個要點:

   1)若是當前線程中沒有session,經過openSession方法來得到一個新的session,並把新的session放到當前線程中;

   2)從當前線程中的到session;

   3)經過getCurrentSession()方法執行CRUD必須要開啓事務;

   4)通常不用手動關閉session;

ide

相關文章
相關標籤/搜索