必须管理实体以调用删除

时间:2012-02-18 05:56:12

标签: java jpa-2.0 eclipselink

这里发生了什么?

@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;
}

在致电remove时,我收到IllegalArgumentException消息为Entity must be managed to call remove: ...., try merging the detached and try the remove again.

2 个答案:

答案 0 :(得分:18)

在您的情况下,不需要合并,因为在 em.find em.remove 之间的任何点都不会释放ac。

通常,当实体被释放时,EntityManager的方法合并将实体作为参数,返回托管实例。作为参数给出的实体不会转换为附加。例如,这里解释了这一点:EntityManager.merge。你必须去:

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

答案 1 :(得分:6)

试试这个:

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