JPA: Deleting detached instance

12,366

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.

Share:
12,366
Sachin J
Author by

Sachin J

Updated on June 04, 2022

Comments

  • Sachin J
    Sachin J almost 2 years

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

  • Sachin J
    Sachin J over 11 years
    Actually, I want to remove only. I just mention merge because, I am get confused that merge is working but remove is not working...