Lost Heaven 0809
Lost Heaven 0809

Reputation: 466

when an entity stops to be managed in JPA

I'm talking about JPA in JavaEE. In a book that i read talk about:

EntityManager em;
em.find(Employee.class, id);

"This is all the information needed by the entity manager to find the instance in the database, and when the call completes, the employee that gets returned will be a managed entity, meaning that it will exist in the current persistence context associated with the entity manager - pro-ejb3-jpa". But i don't know when an entity stop to be managed and i have to merge() to be managed again if i want to update, delete...

Upvotes: 4

Views: 2223

Answers (2)

Koitoer
Koitoer

Reputation: 19543

There are several cases when entities become detached and it depends on the Entity Manager and how the persistence context is associated to it.

  1. As @JB Nizet said, entities become detached when transaction are committed if they belongs to a container manager transaction scope persistence context.
  2. Entities become detached when stateful bean call @Remove method if they belongs to Container manager extended persistence context, here entities still managed after several method invocations, and commit the TX until the stateful bean ends it lifecycle.
  3. If application call the method clear on the entity Manager all the entities become detached. em.clear()
  4. If a TX is marked for rollback all the entities become detached in a transaction scope EM.
  5. If you call the method detach on the entity Manager passed a managed entity as parameter it will Detach the entity. em.detach(java.lang.Object)
  6. In an application Managed Persistence context when you close the entity Manager all the entities become detached. em.close

As you said Merge will take a detached entity and make it managed by the persistence context, basically a detached object is an object in a special state in which they are not managed by any EntityManager but still represent objects in the database.

Based on they comment below and according to the specs

If X is a detached entity, the state of X is copied onto a pre-existing managed entity instance X' of the same identity or a new managed copy X' of X is created

Upvotes: 4

JB Nizet
JB Nizet

Reputation: 692071

By default, the persistence context is bound to the transaction. So the context is closed when the transaction is committed or rolled back. And once its closed, your entity, which was managed by the persistence context, becomes unmanaged.

Upvotes: 5

Related Questions