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