2012-02-18 46 views
13

这里发生了什么?实体必须设法调用删除

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

+0

与em.find(...)方法解决了这个问题。 – 2015-10-07 13:18:37

回答

18

在你的情况的合并是不需要的,因为交流是没有任何一点em.findEM之间deattached .remove

通常,当实体deattached,EntityManager的方法合并需要实体作为参数,收益管理的实例。作为参数给出的实体不会被转换为被附加。这例如在这里解释:EntityManager.merge。你必须去的:

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

奇怪...没有改变那个代码(虽然还有其他不相关的变化),但它神秘地开始工作。我甚至完全取消了合并,因为我首先得到它的全部原因是我得到了这个例外。它不应该是必须的,因为当我们处于加载它的同一个持久化上下文中时,实体应该被连接。我想其他事情正在发生。愚蠢的GlassFish。 – 2012-02-18 07:02:07

+0

不过,我确实接受你的观点,你应该使用从前向合并中返回的对象,而不是传入的对象。 +1 – 2012-02-18 07:02:48

+0

你是绝对正确的,你的代码应该没有合并工作,因为ac在任何时候都没有脱离。我首先认为这是一个过于简单的例子。我会更新答案。 – 2012-02-18 09:10:59

6

试试这个:

entity = getEntityManager().getReference(AppointmentComment.class, entity.getId()); 
getEntityManager().remove(entity); 
相关问题