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

前端 未结 5 1743
执笔经年
执笔经年 2020-12-07 16:32

I have a java EE project using JPA (transaction-type=\"JTA\"), hibernate as provider. I write my beans to handle the CRUD things. The program running in JBOSS 7 AS.

5条回答
  •  孤街浪徒
    2020-12-07 16:59

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

提交回复
热议问题