Hibernate 可以通過sessionFactory.openSession()和sessionFactory.getCurrentSession()來獲得session,下面來淺說一下兩者區別。
【sessionFactory.openSession()】
通過session工廠sessionFactory.openSession()方法來獲得一個session,每次都創建一個新的session出來,並且每次Hibernate都會打開數據庫和應用程序的連接。
【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;