gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:50:23 29 4
gpt4 key购买 nike

我有以下代码:

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/

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