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

时间:2013-09-06 08:35:54

标签: java transactions persistence openjpa

我正在使用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一样简单?

1 个答案:

答案 0 :(得分:2)

是的,请注意以下事项: 根据{{​​3}},它可以抛出IllegalStateException。另外,我想你是在Application Server端,这就是为什么我会考虑下一个通知:

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

@Resource private UserTransaction userTransaction;