3

我正在使用 Spring、JPA 和 Hibernate。

我得到了以下实体:

@Entity
@Table(name = "Supplier")
public class Supplier {

   @Id
   @Column(name = "Supplier_ID", nullable = false)
   private Integer supplierId;

   ...
}

和,

@Entity
@Table(name = "Product")
public class Product {

   @Id
   private Integer productId;

   @ManyToOne(cascade = CascadeType.ALL)
   @OnDelete(action = OnDeleteAction.CASCADE)
   @JoinColumn(name = "Supplier_ID")
   private Supplier supplier;

   ...
}

现在,我的问题是,使用给定的架构

  1. 当我从子项(即产品)中删除一行时,供应商也会被删除吗?
  2. 或者,只有当父级(即供应商)被删除时,才会级联删除所有子级“产品”

谢谢。

4

1 回答 1

6

The product will be removed when the supplier is removed due to the OnDelete annotation.

The OnDelete annotation is used only when the schema is generated by Hibernate. It configures the foreign key in database so that when the referenced row is deleted, the row containing the foreign key is also deleted.

See http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#entity-hibspec-singleassoc

But Hibernate will also delete the supplier when you delete the product (which is probably not what you want), because of the CascadeType.ALL set on the association. You should remove this attribute: there is no reason to delete a supplier when one of its product is removed.

于 2012-06-06T13:37:36.393 回答