Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA: Deleting detached instance

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...

like image 861
Sachin J Avatar asked Dec 27 '22 16:12

Sachin J


1 Answers

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.

like image 93
Piotr Nowicki Avatar answered Dec 30 '22 11:12

Piotr Nowicki