JPA实体关系:级联删除 [英] JPA Entity relationship: Cascade on delete

查看:808
本文介绍了JPA实体关系:级联删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有以下实体:

  @Entity 
@Table(name =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供应商供应商;

...
}

现在,我的问题是,如果我从子(即产品)删除一行,供应商也会被删除吗?


  1. li>
  2. 或者,只有在Parent(即。供应商)被删除后,才会级联删除所有子产品

谢谢。

解决方案

由于OnDelete注释。



OnDelete注释仅在Hibernate生成架构时使用。它在数据库中配置外键,以便删除被引用的行时,包含外键的行也被删除。



请参阅



但是当你删除产品时,Hibernate也会删除供应商(这可能不是你想要的) ,因为在关联上设置了CascadeType.ALL。您应该删除该属性:当其中一个产品被移除时,没有理由删除供应商。


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.

解决方案

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.

这篇关于JPA实体关系:级联删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆