thrau
thrau

Reputation: 3100

How do I distinguish a detached from a removed entity?

As stated in both the JPA 1 and the Hibernate documentation 2, the state of a removed entity is defined as follows:

Removed: a removed entity instance is an instance with a persistent identity, associated with a persistence context, but scheduled for removal from the database.

As far as I understand, removed Entities are no longer managed, which is why EntityManager#contains(Object) returns false on removed objects, despite them being associated with the persistence context, and the method being documented as:

Check if the instance is a managed entity instance belonging to the current persistence context.

That means, the following two code snippets will yield the same result:

// omitted transaction
em.remove(entity);
entity.getId(); // returns the entity id
entity.contains(entity); // false (?)

 

em.detach(entity);
entity.getId(); // returns the entity id
em.contains(entity); // false

So how do I determine the association of a removed entity with a persistence context? How do I distinguish a detached from a removed entity?

Upvotes: 1

Views: 1027

Answers (3)

Rishav Basu
Rishav Basu

Reputation: 401

Instead of em.contains(entity) call em.getReference(Entity.class, id). If javax.persistence.EntityNotFoundException is thrown then it means the entity is removed.

Upvotes: 0

Ankur Singhal
Ankur Singhal

Reputation: 26077

If you try to fetch or do some operation on detach entity, it will throw you an exception.
On the other hand, for the removed entity, it will either fetch you until your transaction have not been flushed or return null since it will not be in database also.

Also load() and get() , method can be used here.

session.load()

It will always return a “proxy” (Hibernate term) without hitting the database. In Hibernate, proxy is an object with the given identifier value, its properties are not initialized yet, it just look like a temporary fake object.
If no row found , it will throws an ObjectNotFoundException.

session.get()

It always hit the database and return the real object, an object that represent the database row, not proxy.
If no row found , it return null.

Upvotes: 1

Ankur Singhal
Ankur Singhal

Reputation: 26077

detached - the entity has an associated identifier, but is no longer associated with a persistence context (usually because the persistence context was closed or the instance was evicted from the context)

removed - the entity has an associated identifier and is associated with a persistence context, however it is scheduled for removal from the database.

It will be removed once the transaction is flushed.

Upvotes: 0

Related Questions