3

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?

itsadok
  • 28,822
  • 30
  • 126
  • 171

2 Answers2

7

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]

Jasper
  • 2,166
  • 4
  • 30
  • 50
3

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

DataNucleus
  • 15,497
  • 3
  • 32
  • 37
  • Can you elaborate? How do I change the persistence context? – itsadok Jul 19 '11 at 07:12
  • Well the JPA spec (section 3.3) would be a good read, but also http://www.datanucleus.org/products/accessplatform_3_0/jpa/object_lifecycle.html In DataNucleus we provide a persistence property to allow the user to choose. In standard JPA you default to "extended" for JSE usage, and "transaction" for JEE usage. What Hibernate allows, no idea – DataNucleus Jul 19 '11 at 07:52
  • @DataNucleus In JPA 2.0 Spec , it's montioned that rollback cause managed entities of both transaction-scoped and extended persistence context to become detached , check ch. 3.3.2 http://download.oracle.com/otn-pub/jcp/persistence-2.0-fr-oth-JSpec/persistence-2_0-final-spec.pdf – Mifmif Jun 22 '17 at 19:30