Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

jpa

jpql

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

like image 660
Ivan Vilanculo Avatar asked Apr 21 '15 14:04

Ivan Vilanculo


4 Answers

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);
like image 155
Robby Cornelissen Avatar answered Oct 17 '22 20:10

Robby Cornelissen


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();
like image 36
Ivan Vilanculo Avatar answered Oct 17 '22 20:10

Ivan Vilanculo


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, i.e. 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.

like image 2
Alexey Malev Avatar answered Oct 17 '22 20:10

Alexey Malev


remove the

em.detach(stock);

detach removes your entity from the entityManager

like image 2
griFlo Avatar answered Oct 17 '22 21:10

griFlo