java - 如何获得事务回滚和对象的初始状态退休

标签 java hibernate jpa transactions rollback

我不确定这是否正确,但我需要在事务回滚后,我的对象返回其初始状态。我创建了一个 junit 测试,但它失败了。

try {
    entityManager.getTransaction().begin();
    entityManager.persist(itemBec);
    //            throw new Exception("teste");
    //            throw new EJBTransactionRolledbackException("teste");
    //            throw new ConstraintViolationException("teste", null, null);
    throw new RuntimeException("teste");
} catch (Exception e) {
    entityManager.getTransaction().rollback();
} finally {
    if (entityManager.getTransaction().isActive()) {
        entityManager.getTransaction().commit();
    }
}
entityManager.close();
factory.close();
Assert.assertNull(itemBec.getId());

我假设对象必须返回其初始状态是否错误?

谢谢。

最佳答案

Am I wrong to assume that the object must return do its initial state?

Hibernate 不会回滚对象状态。最好不要跨事务重用对象,这样就不会出现这样的问题。

来自 this answer引用 spec (重点是我的):

Transaction Rollback

For both transaction-scoped and extended persistence contexts, transaction rollback causes all pre-existing managed instances and removed instances [31] to become detached. The instances’ state will be the state of the instances at the point at which the transaction was rolled back. Transaction rollback typically causes the persistence context to be in an inconsistent state at the point of rollback. In particular, the state of version attributes and generated state (e.g., generated primary keys) may be inconsistent. Instances that were formerly managed by the persistence context (including new instances that were made persistent in that transaction) may therefore not be reusable in the same manner as other detached objects—for example, they may fail when passed to the merge operation. [32]

这就是为什么我认为最好不要跨事务重用实体:虽然只要事务成功提交它就可以工作,但如果事务失败,事情就会变得更加复杂。通常,无论如何都没有令人信服的理由来跨事务重用实体。

关于java - 如何获得事务回滚和对象的初始状态退休,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16714569/

相关文章:

java - 为什么 Eclipse 构建路径中需要 oracle 驱动程序?

java - Hibernate 仅在基本类型上指定一次 @Column 注解

java - Hibernate中的单向一对多映射产生冗余更新

java - 当另一个事务删除惰性子级时的 JPA-Hibernate 行为

java - BeanIO InvalidRecordGroupException 给出错误的行号

java - JRadiobutton 选择未显示

java - 连接到两个数据库时出现 LazyInitializationException

java - Hibernate 延迟加载字段

java - 奇怪的java.io.NotSerializedException : org. springframework.dao.support.PersistenceExceptionTranslationInterceptor

java - 如何附加到正在运行的 jar 并调试它?