jpa - JPQL 更新查询执行更新时事务需要异常

标签 jpa transactions sql-update jpql entitymanager

当我尝试运行此代码时收到此错误。

错误:

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/

相关文章:

java - Spring 数据 JPA : Fetching data from entity just after save() method

mysql - Hibernate 按可能为空的字段排序

java - @Transactional 在 Spring Boot 中不起作用

mysql - 根据 MySQL 中的 WHERE 子句创建具有不同值的重复更新

java - 关系未设置为一对多关系

java - 无法检测 JPA 与 JBoss 使用的数据库

iOS 6 应用内购买 - 无需使用需要用户密码的 'restoreCompletedTransactions' 即可访问已完成的交易数据

node.js - 使用 NodeJS 和 Postgres 的事务链中的可选 INSERT 语句

mysql - 有什么方法可以区分 MYSQL 更新的 0 行受影响的情况?

mysql - 使用子查询更新表