[英]when deleting a spring object, that has manyToMany relationship how do i avoid the “cant delete or update a parent row ” error?
when deleting a spring object, that has manyToMany relationship with another spring object - how do i avoid the "cant delete or update a parent row, a foreign key constraint fails " error?删除与另一个 spring 对象具有 manyToMany 关系的 spring 对象时 - 如何避免“无法删除或更新父行,外键约束失败”错误?
this is the method that is failing.这是失败的方法。
(coupon is the spring object we are attempting to delete) (优惠券是我们试图删除的弹簧对象)
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");
}
this is the mapping of the relationship with the other object "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;
and this is the error that spring gives:这是 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`))
You need to define a one to many relation in Customer and Coupon object.您需要在 Customer 和 Coupon 对象中定义一对多关系。 The relationship currently does not look correct.
这种关系目前看起来不正确。 One customer may have many coupons so a customer object will contain a one to many relationship with the coupons object and use cascade = CascadeType.REMOVE options for foreign key issues.
一个客户可能有许多优惠券,因此客户对象将包含与优惠券对象的一对多关系,并使用级联 = CascadeType.REMOVE 选项解决外键问题。 In database you should also add this option if not existing already.
在数据库中,如果不存在,您还应该添加此选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.