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

后端 未结 2 1398
灰色年华
灰色年华 2021-01-31 14:34

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

相关标签:
2条回答
  • 2021-01-31 15:03

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

    0 讨论(0)
  • 2021-01-31 15:08

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

    0 讨论(0)
提交回复
热议问题