在開發電子化自動支付的開關功能過程中,遇到了一個很有意思的問題,no session for current thread,查找資料,這句話的大概意思是說當前線程不存在會話管理,查找代碼配置文件,採用的事務管理是通過註解的方式進行配置管理,而且項目是已經生產運行了很久,不存在不管理事務的情況,那麼唯一的情況,就是自己調用的數據庫查詢方法有誤了。
我們看一下事務配置管理文件:
排除了這個問題,那麼可能就是自己調用的dao接口錯誤了,我們看一下出錯的這段代碼邏輯(由於就新增了一段代碼,很容易就確定問題出在哪,不需要dubug模式確定問題根源了):
// 授權支付失敗 退還額度
boolean isUseNewStandard = false;
String hql = " from AdmdivCode a where a.moneyCorpCode='Y' and a.admdivCode='" + ecfnPay.getAdmDivCode() + "'";
List<AdmdivCode> adCodes = publicDao.find(hql);
if (adCodes != null && adCodes.size()> 0) {
isUseNewStandard = true;
}
可以確定的是,就是這段代碼(查詢)的地方報錯,那麼,我們看下dao接口:
public interface PublicDao<T> {
public List<T> find(String hql);
public List find_SS(String hql);
}
public class PublicDaoImpl implements PublicDao {
@Override
public List find(String hql) {
return this.getCurrentSession().createQuery(hql).list();
}
@Override
public List find_SS(String hql) {
Session ss = sessionFactory.openSession();
Transaction ts = ss.beginTransaction();
List datas = null;
try {
datas = ss.createQuery(hql).list();
ts.commit();
} catch (HibernateException e) {
ts.rollback();
e.printStackTrace();
throw e;
} finally {
ss.close();
}
return datas;
}
}
Hibernate與spring集成之後,如果需要獲取session,並且使用getCurrentSession(),就會報這個錯:“No Session found for current thread”。我們看一下代碼,我們的確用的是find()而非find_SS(),查看其實現,就知道這個錯誤的原因了,改下調用方法,問題解決。
我們程序採用配置TranactionManager的方式進行事務管理,並且通過申明的方式引入事務(@Service),這裏也可以通過@Transactional的方式,配置完畢,Spring會在開始事務之前通過AOP的方式爲當前線程創建Session,此時調用getCurrentSession()將得到正確結果。
由於實現方法中,find_SS()已經自己開啓session,所以我們調用find_SS即可,若無該方法,我們可以按照如上的方式進行解決。