当我尝试运行此代码时收到此错误。
错误:
javax.persistence.TransactionRequiredException:通过容器管理的事务性EntityManager的非事务性访问获取的查询对象不支持executeUpdate
代码:(_ut是一个UserTransaction对象)
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();
}
}
我还有其他实现相同的函数,它们不会抛出此错误。
如有任何建议,我们将不胜感激。
谢谢。
最佳答案
您正在使用EntityManager
来获取命名查询,并且还使用(我认为是)注入(inject)的UserTransaction
。
看到错误消息显示“...通过非事务访问获取的查询对象...”。这意味着您将通过非事务访问获取“NamedQuery”,因为 EntityManager
与 _ut
不在同一事务中。因此,您首先将 EntityManager
加入到 UserTransaction
,然后获取并执行查询。
最后你的 block 应该看起来像:
@PersistenceContext(unitName = "myPU")
EntityManager em;
@Inject
UserTransaction ut;
public void doSomeStuff()
{
ut.begin();
em.joinTransaction();
em.createNamedQuery("query1").executeUpdate();
ut.commit();
}
关于jpa - JPQL 更新查询执行更新时事务需要异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15753112/