Sachin J
Sachin J

Reputation: 2201

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

Upvotes: 6

Views: 15377

Answers (2)

Piotr Nowicki
Piotr Nowicki

Reputation: 18224

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.

Upvotes: 12

Shervin Asgari
Shervin Asgari

Reputation: 24517

A quick search reveals that you need to do this in the same transaction. You cannot merge and then delete. You need to do it in the same transaction, or separate them in two transactions

Upvotes: 1

Related Questions