JPA: Deleting detached instance

Sachin J picture Sachin J · Oct 17, 2012 · Viewed 11.5k times · Source

I get resultList from typedQuery object. I take first object from that list.

eg. LoginAttempt loginAttempt = loginAttempts.get(0);

When, I update this object and call entityManager.merge(loginAttempt); it is updated successfully.

But when I am going to delete this object it gives me exception ie. java.lang.IllegalArgumentException: Removing a detached instance.

Any suggestion. Thanks :)

Actually, I want to remove only. I just mention merge because, I am get confused that merge is working but remove is not working...

Answer

Piotr Nowicki picture Piotr Nowicki · Oct 17, 2012

Merge is actually working because it's purpose is to transit from detached to managed state. Remove, on the other hand, can work only on managed entities.

If you have a managed entity, you can invoke em.remove(-) on it.
If you have a detached entity, you should invoke Object managed = em.merge(detached) and then em.remove(managed). You must do this within the same transaction boundaries.