Entity must be managed to call remove when I try to delete an entity
Solution 1
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);
Solution 2
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();
Solution 3
remove the
em.detach(stock);
detach removes your entity from the entityManager
Solution 4
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.
Solution 5
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();
}
Ivan Vilanculo
The Greater Life bug is being afraid of making mistakes. U'll learn by them.
Updated on June 09, 2022Comments
-
Ivan Vilanculo almost 2 years
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
-
Ivan Vilanculo about 9 yearsthank you, I did not see the em.deach line (stock) changed the code as suggested and it worked