JPA Entity relationship: Cascade on delete

假装没事ソ 提交于 2019-12-06 06:37:03

问题


I am using spring, JPA with Hibernate.

I got the following entities:

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

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

   ...
}

and,

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

   ...
}

Now, my question is, with the given schema

  1. when I delete a row from child ( ie. Product), will the Supplier will also get deleted?
  2. Or, it is only when the Parent (ie. Supplier) get deleted then it is cascaded to delete all the child 'Products'

Thanks.


回答1:


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.



来源:https://stackoverflow.com/questions/10913715/jpa-entity-relationship-cascade-on-delete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!