createQuery without an active transaction

我们使用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之类的操作了。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值