Question: 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**

Answer: 
[`EntityManager.contains()`](http://download.oracle.com/javaee/6/api/javax/persistence/EntityManager.html#contains%28java.lang.Object%29)

> 
> Check if the instance is a managed entity instance belonging to the current persistence context. 
> 
> 
>
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.

```java
/**
 * 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();
        }
    }

```