javax.persistence.Entitymanager: remove() method

sachinpkale picture sachinpkale · Jul 18, 2012 · Viewed 62.4k times · Source

Does remove(Object entity) method of EntityManager work only on those objects got from find() method?

I have following code snippet:

public void deletePerson() {
    EntityManager em = getEntityManager();
    Person p = new Person("x", "y", 200);
    em.remove(p);
}

But it is not removing the particular entry from database.

When I tried something like below:

public void deletePerson() {
    EntityManager em = getEntityManager();
    Person p = em.find(Person.class, 200);
    em.remove(p);
}

It's working fine.

Answer

JMelnik picture JMelnik · Jul 18, 2012

Quoting from ObjectDB's manual on deleting JPA entity objects:

In order to delete an object from the database it has to first be retrieved (no matter which way) and then in an active transaction, it can be deleted using the remove method.

An IllegalArgumentException is thrown by remove if the argument is not a an instance of an entity class or if it is a detached entity.

When creating object with new operator, it becomes a detached entity, you need to persist it if you want to remove it.

When retrieving entity, you are retrieving persistent entity.