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

Solution 1:

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

Solution 2:

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.)