解决Hibernate / JPA EntityNotFoundException的技巧

时间:2010-03-18 02:34:40

标签: java hibernate jsf jpa

我遇到了 Hibernate 的问题,当我尝试删除一组实体时遇到以下错误:

javax.persistence.EntityNotFoundException: deleted entity passed to persist: [com.locuslive.odyssey.entity.FreightInvoiceLine#<null>]

这些通常很难追踪,因为它们通常是由实体被删除而不是从它所属的Collection中删除而引起的。

在这种情况下,我已经从我能想到的每个列表中删除了实体(这是一个复杂的数据模型)。我把JBoss登录到Trace中,我可以看到正在级联的集合。但是,我似乎无法找到包含我正在删除的实体的Collection。

有没有人有解决此特定异常的任何提示?我特别想找到方法来确定可能拥有的收藏品。

感谢。

2 个答案:

答案 0 :(得分:3)

终于找到了它,这正是我所期待的那种令人沮丧的“找到清单”。

执行删除的代码是扩展Seam的EntityHome。

public class FreightInvoiceHome extends EntityHome<FreightInvoice> {
    public void deleteLine(FreightInvoiceLine freightInvoiceLine) {
      getEntityManager().remove(freightInvoiceLine);
      freightInvoiceLine.getShipInstrLineItem().getFreightInvoiceLines().remove(freightInvoiceLine);

      /* These next two statements are effectively performing the same action on the same FreightInvoice entity
       * If I use the first one then I get the exception. If I use the second one then all is ok.
       */
      getInstance().getFreightInvoiceLines().remove(freightInvoiceLine);
      //freightInvoiceLine.getFreightInvoice().getFreightInvoiceLines().remove(freightInvoiceLine);
    }
}

我曾怀疑这可能是由一个狡猾的equals()/ hashcode()造成的,但在更换后两者都没有区别。

如果可以解释两者之间的区别,很高兴将接受改为别人。

答案 1 :(得分:2)

我建议你做

  

getEntityManager()除去(freightInvoiceLine);

作为最后一步。我认为这是一个很好的做法,首先从任何集合中删除子,然后实际删除它。在许多情况下,它会避免头痛。