java - entityManager.getTransaction().rollback() 分离实体?

标签 java hibernate jpa persistence entitymanager

我有以下代码:

EntityManagerFactory emf = Persistence.createEntityManagerFactory("test")
EntityManager entityManager = emf.createEntityManager()
User user = entityManager.find(User.class, 0);
entityManager.getTransaction().begin();
entityManager.getTransaction().rollback();
entityManager.refresh(user);

这会在第四行抛出一个 IllegalArgumentException,表示“实体不受管理”。如果我将第三行更改为 .commit() 而不是 .rollback(),一切似乎都正常。

这是怎么回事?我可以防止这种情况发生吗?

更新:@DataNucleus 将我引向 PersistenceContext。如何更改代码中的持久性上下文?

最佳答案

来自JSR-000317 Persistence Specification for Eval 2.0 Eval :

3.3.2 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 - entityManager.getTransaction().rollback() 分离实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6743222/

相关文章:

java - hibernate :脏字段跟踪

java - 了解 Hibernate 中的 mappedBy 注解

java : when can a rollback fail in jpa?

java性能: string literal

java - spring boot CrudRepo 定义一个bean

java - Hibernate @OneToOne 为空

hibernate - JPA Hibernate n+1 问题(Lazy & Eager Diff)

java - JPA 对于原始属性也是懒惰的吗?

java - 使用 Eclipse 内存分析器分析堆转储

java - 如何在Swing中输入整数?