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);
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();
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.
remove the
em.detach(stock);
detach removes your entity from the entityManager
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With