Java 删除具有多个关系的spring对象时,如何避免;无法删除或更新父行“;错误?

Java 删除具有多个关系的spring对象时,如何避免;无法删除或更新父行“;错误?,java,sql,spring,spring-boot,Java,Sql,Spring,Spring Boot,删除一个与另一个spring对象有很多关系的spring对象时,如何避免“无法删除或更新父行,外键约束失败”错误 这就是失败的方法 (优惠券是我们试图删除的spring对象) 这是与另一个对象“Customer”的关系映射 您需要在客户和优惠券对象中定义一对多关系。关系当前看起来不正确。一个客户可能有多个优惠券,因此客户对象将包含与优惠券对象的一对多关系,并使用cascade=CascadeType。删除外键问题的选项。在数据库中,如果尚未存在此选项,则还应添加此选项 public void d

删除一个与另一个spring对象有很多关系的spring对象时,如何避免“无法删除或更新父行,外键约束失败”错误

这就是失败的方法

(优惠券是我们试图删除的spring对象)

这是与另一个对象“Customer”的关系映射


您需要在客户和优惠券对象中定义一对多关系。关系当前看起来不正确。一个客户可能有多个优惠券,因此客户对象将包含与优惠券对象的一对多关系,并使用cascade=CascadeType。删除外键问题的选项。在数据库中,如果尚未存在此选项,则还应添加此选项

public void deleteCoupon(Coupon coupon) throws CouponsSystemExceptions {
        if (!companyHasCouponPurchased(coupon)) {
            throw new CouponsSystemExceptions(SystemExceptions.ILLEGAL_ACTION_ATTEMPTED,
                    "The company does not have this coupon");
        }
        couponRepository.delete(coupon);
        System.out.println("\n--The coupon was deleted--\n");
    }
@ToString.Exclude
    @ManyToMany(mappedBy = "coupons")
    private List<Customer> customers;
this is the mapping of the "customer" object relationship with the coupon object
@ToString.Exclude
    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "customers_vs_coupons", joinColumns = @JoinColumn(name = "CUSTOMER_ID"), inverseJoinColumns = @JoinColumn(name = "COUPON_ID"))
    private List<Coupon> coupons;
Exception in thread "main" org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement;

WHICH IS CAUSE BY :
Caused by: java.sql.SQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`coupon_system2`.`customers_vs_coupons`, CONSTRAINT `FKqic70ugf37j3rc4og2t3xp0ah` FOREIGN KEY (`COUPON_ID`) REFERENCES `coupons` (`id`))