EntityManager.getTransaction (). rollback () separates objects?

I have the following code snippet:

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, which says: "Entity not managed". If I change the third line to .commit() instead of .rollback() , everything will work fine.

What's going on here? Can I prevent this?

UPDATE: @DataNucleus directs me to a PersistenceContext. How to change persistence context in my code?

+3
source share
2 answers

From the JSR-000317 save specification for Eval 2.0 Eval :

3.3.2 rollback transactions

For contexts with limited transaction binding and extended persistence contexts, transaction rollback causes all previously existing managed instances and remote instances [31] to become disconnected . The state of the instances will be the state of the instances at the time the transaction was rolled back. Typically, rollback transactions result in a persistence context in an inconsistent state at the time of rollback. In particular, the state of the version attributes and the generated state (for example, generated primary keys) may be inconsistent. Instances that were previously controlled by the persistence context (including new instances that were made permanent in this transaction), therefore, cannot be reused in the same way as other detached objects - for example, they may fail to transfer the merge operation. [32]

+7
source

In the PersistenceContext "Transaction", then commit / rollback separates the objects used in the transaction. In the PersistenceContext of "Extended" then commit / rollback does nothing, and objects are closed when EM is closed. Depends on your context.

+3
source

Source: https://habr.com/ru/post/979965/


All Articles