JPA双向移除

时间:2011-12-08 22:06:02

标签: java jpa

在OpenJPA中,我尝试删除具有到另一个实体的双向映射的实体。我做了“找到”,然后“删除”,但我有一个“遇到删除的对象”的例外。有人能为我提供一个有效的例子吗?

@Entity
@Table(name="Order")
public class Order implements Serializable {
    @EmbeddedId
    private OrderPK pk;
...

    @OneToOne(cascade=CascadeType.ALL, mappedBy="order")
    private Invoice invoice;
}

@Entity
@Table(name="Invoice")
public class Invoice implements Serializable {
    @EmbeddedId
    private InvoicePK pk;
...
    @OneToOne
    @PrimaryKeyJoinColumn   
    private Order order;
}

@Embeddable
public class OrderPK implements Serializable {
    private String id;
    private Date date;
...
}

@Embeddable
public class InvoicePK implements Serializable {
    private String id;
    private Date date;
...
}

首先,我将它们添加到一个事务中并提交:

Order order = new Order(...);
order.set...
Invoice invoice = new Invoice(...);
invoice.set...
order.setInvoice(invoice);
invoice.setOrder(order);
em.persist(order);

然后,当我尝试删除订单时,我预计发票也会消失:

Order order = em.find(Order.class, orderPK); em.remove(order);

但我有一个例外,而是说:

Encountered deleted object "org.apache.openjpa.enhance.Order$pcsubclass-
Order-OrderPK@92882281" in persistent field "Invoice.order" of managed 
object "Invoice$pcsubclass-InvoicePK@92882281" during flush.

0 个答案:

没有答案