java.lang.IllegalArgumentException: Removing a detached instance com.test.User#5

Solution 1:

EntityManager#remove() works only on entities which are managed in the current transaction/context. In your case, you're retrieving the entity in an earlier transaction, storing it in the HTTP session and then attempting to remove it in a different transaction/context. This just won't work.

You need to check if the entity is managed by EntityManager#contains() and if not, then make it managed it EntityManager#merge().

Basically, the delete() method of your business service class should look like this:

em.remove(em.contains(entity) ? entity : em.merge(entity));

Solution 2:

In my case, I got the same error, when I tried to delete an object using,

session.delete(obj)

without creating any transaction before that.

And the problem is solved by creating the transaction first(session.beginTransaction() and then deleting the object.

I hope my answer will help someone :)

Solution 3:

Sometimes its simply because you are missing the @Transaction annotation for add, remove, update operations.