【问题标题】:What is the proper way to clean up an open transaction after PersistenceException?在 PersistenceException 之后清理打开的事务的正确方法是什么?
【发布时间】:2013-09-06 08:35:54
【问题描述】:

我正在使用带有单个持久性单元的 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);
    }

我知道事务没有自动清理,因为我下次运行相同的操作时收到错误消息This operation cannot be performed while a Transaction is active.

是否就像将entityManager.getTransaction().rollback(); 放在catch 块中一样简单?

【问题讨论】:

    标签: java transactions persistence openjpa


    【解决方案1】:

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

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

    @Resource private UserTransaction userTransaction;
    

    【讨论】:

    • 好的,谢谢。关于IllegalStateException - 在进行回滚之前,我是否需要检查getTransaction().isActive() 是否为真?
    • 在您的示例中,我不会检查,因为事务无法处于活动状态的情况很少。也许我会检查逻辑是否在不同的类之间吐出(但不是你的情况)。
    猜你喜欢
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    • 2020-10-24
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    相关资源
    最近更新 更多