简体   繁体   English

如何在包含一对多关系的类中执行删除操作

[英]How to perform delete operation in classes which consists one to many relationship

This is my product Entity
   
 @Entity
    public class Product {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private int id;
    
        @NotNull
        private String name;
    
        private String cancellable;
        private String returnable;
        @NotNull
        private String brand;
        private boolean active;
        @JsonIgnore
        @OneToMany(mappedBy = "product",cascade = CascadeType.ALL)
        private Set<ProductVariation> productVariationSet;
    }

    
This is Product Variant Entity

    @Entity
    public class ProductVariation {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private int id;
    
        private String ProductName;
    
        @NotNull
        private int quantityavailable;
        @NotNull
        private int price;
    
    
        private String details;
   
    
        @JsonIgnore
        @ManyToOne
        @JoinColumn(name = "product_id")
        private Product product;
    
     }
    
    
    

when i am tring to delete products by ID i am getting error like当我试图按 ID 删除产品时,我收到了类似的错误

java.sql.SQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails ( mywebapp . product_variation , CONSTRAINT FKpryf02se86hpv5v7xn5afye4v FOREIGN KEY ( product_id ) REFERENCES product ( id )) product :无法删除或更新父行:外键约束失败( mywebapp product_variation ,CONSTRAINT FKpryf02se86hpv5v7xn5afye4v )( product_id参考) id

How i can correct this error and delete product so its all variant is also delete.我如何更正此错误并删除产品,使其所有变体也被删除。

The cascade operation in Product class as you defined it deletes the product's variants automatically.您定义的产品 class 中的级联操作会自动删除产品的变体。 Just remove @JsonIgnore from field 'private Set productVariationSet' and from field 'private Product product'.只需从字段“private Set productVariationSet”和字段“private Product product”中删除@JsonIgnore。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM