gpt4 book ai didi

java - 在 PersistenceException 之后清理打开的事务的正确方法是什么?

转载 作者:行者123 更新时间:2023-11-30 04:14:54 26 4
gpt4 key购买 nike

我使用带有单个持久性单元的 OpenJPA 2.0。

在我的 persistence.xml 中,我选择使用配置 transaction-type="RESOURCE_LOCAL" 并手动管理事务。

现在,在下面的代码中,如果抛出(并捕获)PersistenceException,我应该如何清理事务?

    try {
entityManager.getTransaction().begin();
MyClassPO myClassPO = (MyClassPO) entityManager
.createQuery("select bn from myClassPO bn where bn.xxx = :xxx")
.setParameter("xxx", xxx)
.getSingleResult(); // NoResultException gets thrown here

... do some more stuff ...

entityManager.getTransaction().commit();

} catch (PersistenceException e) {

// what should I do with the open transaction here ??

logger.error(e);
throw new MyOtherException(e);
}

我知道事务不会自动清理,因为下次运行相同的操作时,我会收到错误消息当事务处于 Activity 状态时无法执行此操作。

就像将 entityManager.getTransaction().rollback(); 放入 catch block 一样简单吗?

最佳答案

是的,但有以下通知:根据documentation ,它可能会抛出 IllegalStateException。另外,我想您位于应用程序服务器端,这就是为什么我会考虑下一个通知:

或者,您可以切换回 JTA,使用 Bean-Managed-Transaction 自行管理 JTA 事务,并使用 UserTransaction

@Resource private UserTransaction userTransaction;

关于java - 在 PersistenceException 之后清理打开的事务的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18653396/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com