Exception in thread "main" org.hibernate.HibernateException: No Session found for current thread
阿新 • • 發佈:2018-12-28
背景
使用spring框架整合Hibernate的時候,通過getCurrentSession()獲得與執行緒繫結的session時,可能會遇到no session found for current thread的錯誤;
原因:呼叫getCurrentSession()之前,沒有呼叫SessionFactory.openSession()開啟session。
解決方案分兩種情況
1、如果沒有配置TranactionManager事務,那麼呼叫getCurrentSession()之前,先呼叫SessionFactory.openSession();
2、如果配置了TranactionManager事務
2.1、在需要宣告事務的方法上面@Transactional
@Transactional public void purchase(String username, String isbn) { // 1.根據isbn來查詢價格和庫存 int price = bookShopDaoImpl.findBookPriceByIsbn(isbn); // 2.更新庫存 bookShopDaoImpl.updateBookStock(isbn); // 3.扣除賬戶餘額 bookShopDaoImpl.updateUserAccount(username, price); }
2.2、在配置檔案中使得事務註解生效
<!--使得註解生效 -->
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/>