我们使用spring和hibernate结合,操作数据库最常用可能是HibernateTemplate,HibernateTemplate中集成了很多使用的方法,可惜的是没的createQuery方法,也许我们使用hibernate的时候喜欢使用Query,我们可能会封装hibernateTemplate.getSessionFactory().getCurrentSession()方法得到Session,session创建Query,这是一个方法,但你应该会得到异常 “createQuery without an active transaction”,因为使用hibernateTemplate.getSessionFactory().getCurrentSession(),你是使用的hibernate的事务管理,而你指望spring管理的事物是hibernateTemplate,所以你会提示没有打开事务的异常。
解决方法:1)使用hibernate事务处理,就像上面单独使用hibernate一样,但这也许不是你想要的。
2)使用hibernateTemplate的HibernateCallBack回调:
return hibernateTemplate.executeWithNativeSession(new HibernateCallback<List<T>>() {
public List<T> doInHibernate(
Session session)
throws HibernateException,
SQLException {
return session.createQuery(
"FROM "
+ this.getClass()
.getName()
+ " WHERE id IN (:ids)")
.setParameterList(
"ids",
idList)
.list();
}
});
实际上hibernateTemplate中封装的find方法也很强大,如果熟练使用完全可以替代createQuery的。
备注:如果出现异常:对同一个集合处理不能使用2个session,这是因为getCurrentSession方法出错,导致打开一个新的session,检查配置文件,如果使用tomcat+spring+hibernate 配置hibernate.current_session_context_class 最好为thread,虽然支持jta,配置比较麻烦,而且jta支持多个sessionFactory,即可以跨数据库,比较强大!
如果hibernate+spring出现session没有提交情况,应该是你让spring负责事务处理,而你有使用了hibernate的session,从而脱离spring事务处理,即没的begintransaction和commit之类的操作了。