entityManager.getTransaction().rollback() 分离实体?
我有以下代码:
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。如何更改代码中的持久性上下文?
I have the following piece of code:
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);
This throws an IllegalArgumentException on the fourth line saying "Entity not managed". If I change the third line to .commit()
instead of .rollback()
, everything seems to work fine.
What is going on here? Can I prevent this from happening?
UPDATE: @DataNucleus is directing me towards PersistenceContext. How do I change the persistence context in my code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自 Eval 2.0 Eval 的 JSR-000317 持久性规范:
From the JSR-000317 Persistence Specification for Eval 2.0 Eval:
在“Transaction”的 PersistenceContext 中,提交/回滚将分离事务中使用的对象。在“扩展”的 PersistenceContext 中,提交/回滚不会执行类似操作,并且对象会在 EM 关闭时分离。取决于您的具体情况
In a PersistenceContext of "Transaction" then commit/rollback will detach objects used in the transaction. In PersistenceContext of "Extended" then commit/rollback do nothing like that, and objects are detached at close of the EM. Depends on your context