Entity must be managed to call remove

元气小坏坏 提交于 2019-12-04 16:42:55

问题


What's going on here?

@Stateless
@LocalBean
public class AppointmentCommentDao {
    public void delete(long appointmentCommentId) {
        AppointmentComment ac = em.find(AppointmentComment.class, appointmentCommentId);
        if (ac != null)
        {
            em.merge(ac);
            em.remove(ac);
        }
    }
    @PersistenceContext
    private EntityManager em;
}

On the call to remove I get an IllegalArgumentException with the message being Entity must be managed to call remove: ...., try merging the detached and try the remove again.


回答1:


In your case merge is not needed, because ac is not deattached in any point between em.find and em.remove.

In general when entity is deattached, EntityManager's method merge takes entity as argument and returns managed instance. Entity given as argument does not transform to be attached. This is explained for example here: EntityManager.merge. You have to go for:

    AppointmentComment toBeRemoved = em.merge(ac);
    em.remove(toBeRemoved);



回答2:


Try this:

entity = getEntityManager().getReference(AppointmentComment.class, entity.getId());
getEntityManager().remove(entity);


来源:https://stackoverflow.com/questions/9338999/entity-must-be-managed-to-call-remove

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