是否可以清空本身有外键的表?
我想从表中删除所有行,但该表作为引用同一个表的主键(定义父子行)的字段。
我想我必须首先删除所有子级,然后删除所有父级,但是如何使用 Spring-Data-Jpa 做到这一点?
我所做的是
@Query("DELETE FROM article a WHERE a.geniusClientId = :geniusClientId")
...但在某些情况下我会遇到违规约束异常。
我使用的数据库是MariaDB。
这是我的实体的摘录:
@Entity(name = "article")
public class Article extends AbstractSynchronizable implements Serializable {
public static final String COLOR_VARIANT_REFERENCE = "color";
public static final String SIZE_VARIANT_REFERENCE = "size";
@Id
@Type(type = "uuid-char")
private UUID id;
@OneToMany(mappedBy = "article", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Set<Image> images;
private String label;
private long vatInclusivePrice;
private long vatExclusivePrice;
private long taxRate;
private long supplierVatInclusivePrice;
private long supplierVatExclusivePrice;
private long supplierTaxRate;
private long oldPrice;
private long stock;
private String reference;
private String description;
private String barcode;
@JoinColumn(name = "parent_id")
@ManyToOne
private Article parent;
...
}
最佳答案
我认为您只需要在实体中添加一个注释:
@ManyToOne(cascade=CascadeType.REMOVE)
private Article parent;
或者:
@ManyToOne(orphanRemoval=true)
private Article parent;
看一下:
关于java - Spring-Data-Jpa - 清空带有外键的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48187905/