Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

entityManager.getTransaction().rollback() detaches entities?

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?

like image 751
itsadok Avatar asked Feb 06 '26 00:02

itsadok


1 Answers

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]

like image 157
Jasper Avatar answered Feb 08 '26 13:02

Jasper