是否可以清空本身带有外键的表?

我想从表中删除所有行,但将此表作为引用同一表(定义父子行)的主键的字段删除。

我想我必须先删除所有子项,然后再删除所有父项,但是如何使用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;


看一眼 :


Cascading Remove
Orphan Removal

关于java - Spring-Data-Jpa-清空一个带有外键的表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48187905/

10-12 05:03