JPQL更新查询的执行更新时事务必需的异常 [英] Transaction required exception on execute update for JPQL update query
问题描述
尝试运行此代码时出现此错误.
I get this error when I try to run this code.
错误:
javax.persistence.TransactionRequiredException:通过容器管理的事务性EntityManager的非事务访问获得的Query对象不支持executeUpdate
javax.persistence.TransactionRequiredException: executeUpdate is not supported for a Query object obtained through non-transactional access of a container-managed transactional EntityManager
代码:(_ ut是一个UserTransaction对象)
Code: (_ut is a UserTransaction object)
public void setMainCategory(Integer deptId,Integer catId){
public void setMainCategory(Integer deptId, Integer catId) {
try {
Query setmain = _entityManager.createNamedQuery("Category.setAsMain");
Query removeMain = _entityManager.createNamedQuery("Category.removeMain");
setmain.setParameter("categoryId", catId);
Department d;
d=_entityManager.find(Department.class, deptId);
removeMain.setParameter("department", d);
_ut.begin();
removeMain.executeUpdate();
_ut.commit();
_ut.begin();
setmain.executeUpdate();
_ut.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
我还有其他在实现上相同的功能,它们不会引发此错误.
I have other functions that are identical in implementation and they do not throw this error.
任何建议将不胜感激.
谢谢.
推荐答案
您正在使用EntityManager
获取命名查询,并且还使用了(我认为是)注入的UserTransaction
You are using an EntityManager
to get the Named Queries and also using an (what I think is) injected UserTransaction
.
看到错误消息显示为"...通过非事务访问获得的查询对象..." .这意味着您将通过非事务访问获得"NamedQuery" ,因为EntityManager
与_ut
不在同一事务中.因此,首先将EntityManager
加入UserTransaction
,然后获取并执行查询.
See that the error message says "...Query object obtained through non-transactional access...". This means you are getting the "NamedQuery" through non-transactional access, because the EntityManager
is not in the same transaction as _ut
. So, you first join the EntityManager
to the UserTransaction
then you get and execute the query.
最后,您的区块应如下所示:
Finally your block should look like:
@PersistenceContext(unitName = "myPU")
EntityManager em;
@Inject
UserTransaction ut;
public void doSomeStuff()
{
ut.begin();
em.joinTransaction();
em.createNamedQuery("query1").executeUpdate();
ut.commit();
}
这篇关于JPQL更新查询的执行更新时事务必需的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!