简体   繁体   中英

Entity must be managed to call remove when I try to delete an entity

I have this method to delete the entity selected in the list. but when called generates this error and I can not see why.

java.lang.IllegalArgumentException: Entity must be managed to call remove: HP Envy 15, try merging the detached and try the remove again.

public void delete(Stock stock){
        EntityManager em = ConnectionFactory.createEntityManager();
        em.getTransaction().begin();
        em.detach(stock);
        em.remove(stock);
        em.getTransaction().commit();        
        em.close();
    }

I've read other related posts

Entity must be managed to call remove

IllegalArgumentException: Entity must be managed to call remove

You can't remove the entity if it is not attached. If the entity is still attached, you can remove it as-is. If it is no longer attached, you can re-attach it using merge :

if (!em.contains(stock)) {
    stock = em.merge(stock);
}

em.remove(stock);

You detach an entity from a session, and then delete it. That won't work.

Try removing em.detach(stock); and pass some entity to the method which is guaranteed to be attached to the session, ie fetch something from DB and then delete it at once. If that works, you are using your method in a wrong way, most likely with detached or just-created entities.

remove the

em.detach(stock);

detach removes your entity from the entityManager

Why do you detach the object ? An IllegalArgumentException is thrown by detach if the argument is not an entity object. If the argument stock is managed by entity manager, delete the detach line, else merge the entity.

Try this:

public void delete(Stock stock){
        EntityManager em = ConnectionFactory.createEntityManager();
        em.getTransaction().begin();
        Stock mStock2 = em.merge(stock);
        em.remove(mStock2);
        em.getTransaction().commit();        
        em.close();
    }

Very thanks guys You helped me to heal my head ache Here is the code after correcting the error

EntityManager em = ConnectionFactory.createEntityManager();
em.getTransaction().begin();
if (!em.contains(stock)) {
    current = em.merge(stock);
}
em.remove(current);
em.getTransaction().commit();
em.close();

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