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

て烟熏妆下的殇ゞ 提交于 2019-11-28 03:47:56
BalusC

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));

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 :)

murali101002

I faced the same problem. The detached entity should be re-attached. As @BalusC mentioned, using EntityManager.merge() should be used to attach the detached entity. EntityManager.merge() generates SQL Query which fetches the current state of the entity, on which EntityManager.remove() has to be performed. But in my case it didn't worked. Try EntityManager.remove(EntityManager.find(Class<T>,arg)) instead. It worked for me.

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

In my experience, if I query an object from the DB then closed the entity manager then do a DB delete, the problem happens. Or if I copy that loaded object to another instance then do a delete, this problem also happens. In my opinion there are 2 things to keep note:

  • The object must be in the same session that was created by the Entity Manager
  • And the object mustn't be transferred to another object while the Entity Manager's session is still opened.

Cheers

Sometimes you can just get id from detached instance, then use direct query to database.As example

String petId = pet.getId().toString();
entityManager.createQuery("DELETE FROM Pet pet WHERE id=" + petId).executeUpdate();

After you can clean context

if (em.contains(pet)){
     em.remove(pet);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!