JPA thinks I'm deleting a detached object

前端 未结 7 2220
萌比男神i
萌比男神i 2020-12-14 00:30

I\'ve got a DAO that I used to load and save my domain objects using JPA. I finally managed to get the transaction stuff working, now I\'ve got another issue.

In my

7条回答
  •  甜味超标
    2020-12-14 00:46

    Transaction ensures the ACID properties but not whether the entity is attached or detached. Even if you are running entityManager.find and entityManager.remove() in the same transaction , there is not guarantee that the entity will be attached. So before issuing entityManager.remove() check if the entity is attached, if not attach it using enitityManger.merge(entity) and then issue entityManager.remove on it as follows:

    @Transactional
     public void delete (long id)
        {
    ModelObj modelObj=entityManager.find(ModelObj.class,id);
    modelObj=entityManager.contains(modelObj)?modelObj:entityManager.merge(modelObj);
            em.remove (modelObj);
        }
    

提交回复
热议问题