必须管理实体以调用删除

这里发生了什么?

@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.

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

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

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

尝试这个:

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