entityManager.getTransaction()。rollback()分离实体? [英] entityManager.getTransaction().rollback() detaches entities?

查看:141
本文介绍了entityManager.getTransaction()。rollback()分离实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下一段代码:

$ p $ 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);

这会在第四行显示Entity not managed的IllegalArgumentException异常。如果我将第三行更改为 .commit()而不是 .rollback(),一切似乎都正常。



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



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

解决方案

JSR-000317 Eval 2.0 Eval的持久性规范


3.3.2事务回滚



对于事务范围和扩展持久化上下文,事务回滚会导致所有预先存在的托管实例和移除实例
[31]
以变为分离
。实例的状态将是事务回滚时实例的
状态。事务回滚通常为
,导致持久化上下文在回滚点处于不一致状态。特别地,版本属性和生成状态(例如,生成的主键)的
状态可能不一致。
以前由持久化上下文管理的实例(包括
的新实例在该事务中持久化)因此可能无法以与其他分离的
对象相同的方式重用 - 例如,传递给合并操作时它们可能会失败。
[32]



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?

解决方案

From the 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]

这篇关于entityManager.getTransaction()。rollback()分离实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆