Marcus Junius Brutus
Marcus Junius Brutus

Reputation: 27296

How to find out whether an entity is detached in JPA / Hibernate?

Is there a way to query the JPA EntityManager whether a given entity is detached? This SO post is discussing a similar issue but does not indicate a way to query the JPA EntityManager on the detachment status of an entity. I would prefer a JPA way, otherwise Hibernate-specific.

Upvotes: 58

Views: 55621

Answers (2)

Steve Chambers
Steve Chambers

Reputation: 39464

Piotr Nowicki's answer provides a way of determining whether an entity is managed. To find out whether an entity has been detached, we'd need to know whether it was previously managed (i.e. came from the database, e.g. by being persisted or obtained from a find operation). Hibernate doesn't provide an "entity state history" so the short answer is there isn't a 100% reliable way of doing this but the following workaround should be sufficient in most cases:

public boolean isDetached(Entity entity) {
    return entity.id != null  // must not be transient
        && !em.contains(entity)  // must not be managed now
        && em.find(Entity.class, entity.id) != null;  // must not have been removed
}

The above assumes that em is the EntityManager, Entity is the entity class and has a public id field that is a @GeneratedValue primary key. (It also assumes that the row with this ID hasn't been removed from the database table by an external process in the time after the entity was detached.)

Upvotes: 34

Piotr Nowicki
Piotr Nowicki

Reputation: 18224

To check if the given entity is managed by the current PersistenceContext you can use the EntityManager#contains(Object entity).

Upvotes: 51

Related Questions