当删除一个spring对象时,它与另一个spring对象有manyToMany关系--如何避免“无法删除或更新父行,外键约束失败”的错误?
这就是失败的方法。
(coupon是我们试图删除的spring对象)
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");
}这是与另一个对象"Customer“的关系的映射
@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;这是spring给出的误差:
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`))发布于 2020-10-01 13:38:43
您需要在客户和优惠券对象中定义一对多关系。关系目前看起来不正确。一个客户可能有许多优惠券,因此一个客户对象将包含与优惠券对象的一对多关系,并使用cascade = CascadeType.REMOVE选项处理外键问题。在数据库中,如果不存在此选项,也应添加此选项。
https://stackoverflow.com/questions/63725539
复制相似问题