use*_*876 6 jpa transactions entitymanager jpql sql-update
我尝试运行此代码时收到此错误.
错误:
javax.persistence.TransactionRequiredException:通过容器管理的事务EntityManager的非事务性访问获得的Query对象不支持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();
}
}
Run Code Online (Sandbox Code Playgroud)
我有其他功能在实现上相同,他们不会抛出此错误.
任何建议将不胜感激.
谢谢.
问题不是来自您的方法实现,而是来自您的执行上下文。
所有更新数据库的方法都必须在打开的事务中执行。确保这一点的方式取决于您管理事务的方式。如果事务是用户管理的,您必须显式检索并加入现有事务或打开一个新事务。如果它是容器管理的,只需@transactional
在您的方法上添加注释或确保您的调用层次结构中有一个方法保存该注释。
在这里,您在容器管理的事务上下文中使用用户管理的事务(请参阅错误消息中的“容器管理的事务 EntityManager”)。您不应该这样开始并自己提交/回滚事务。如果您想这样做,只需检索应用程序管理的 EntityManager 即可正确访问 JTA 事务。
参见 http://docs.oracle.com/cd/E19226-01/820-7627/bnbqy/index.html
归档时间: |
|
查看次数: |
11982 次 |
最近记录: |