简体   繁体   中英

Entity must be managed to call remove?

public Person deletePerson(Person entity) {
    EntityManager ems = emf.createEntityManager();

    try {
        ems.getTransaction().begin();
        ems.merge(entity);
        ems.remove(entity);
        ems.getTransaction().commit();
    } finally {
        ems.close();
    }
    return entity;
}

it doesnt work I don't know why? Gives me java.lang.IllegalArgumentException

It doesn't work because remove operation requires managed entity to be passed to it. You could modify your code like this to make it work:

 entity = ems.merge(entity);
 ems.remove(entity);

Because merge returns managed entity instance, you can call remove with the object it returns, because it is managed by JPA (the object you pass to merge is not affected, which is why your code fails).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM