Manolo Santos
Manolo Santos

Reputation: 1913

How to know if an EclipseLink entity is detached?

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

Upvotes: 4

Views: 4529

Answers (2)

Alex Byrth
Alex Byrth

Reputation: 1499

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();
        }
    }

Upvotes: 0

axtavt
axtavt

Reputation: 242786

EntityManager.contains()

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

Upvotes: 7

Related Questions