4

Do you know any method to know the state of a JPA entity?. I'm facing some bugs and I need to know if an entity is detached or managed.

I'm using EclipseLink 2.1.2

Manolo Santos
  • 1,915
  • 1
  • 14
  • 25

2 Answers2

7

EntityManager.contains()

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

axtavt
  • 239,438
  • 41
  • 511
  • 482
  • 8
    And if the object is managed by a different EntityManager ? it returns false ... which doesn't mean it is detached. – DataNucleus Jan 05 '11 at 17:43
  • [This SO post](https://stackoverflow.com/questions/13135309/how-to-find-out-whether-an-entity-is-detached-in-jpa-hibernate) discusses why @DataNucleus is correct. – Mohamed El-Beltagy Jan 07 '19 at 11:35
0

The previous answer is partially correct.

You must check other states to have a higher degree of confidence.

I use the following code, where I have my own managed EntityManager / EntityManagerFactory.

/**
 * Check if an entity is detached or not
 * @param entity
 * @return true, if the entity is managed
 */
 public boolean isDetached(AbstractEntity entity) {
        // pick the correct EntityManager, somehow
        EntityManager em = getMyEntityManager(entity);
        try {
            if (em == null)
                return false;

            return entity.getID() != null // must not be transient
                    && !em.contains(entity) // must not be managed now
                    && em.find(Entity.class, entity.getID()) != null; // must not have been removed
        } finally {
            if (em != null)
                em.close();
        }
    }
Alex Byrth
  • 1,328
  • 18
  • 23