简体   繁体   中英

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

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 ))

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. Just remove @JsonIgnore from field 'private Set productVariationSet' and from field 'private Product product'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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