我有以下实体:
@Entity
public class Car { ... }
@Entity
public class Driver {
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "CAR_ID")
private Car car;
...
}
@Entity
public class Penalty {
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="D_ID")
private Driver driver;
...
}
我希望在Driver
被删除Penalty
时删除Car
和carRepository.delete(car_id)
的所有信息。
WARN : org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 1451, SQLState: 23000
ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Cannot delete or update a parent row: a foreign key constraint fails (`test`.`car_drivers`, CONSTRAINT `FK9ux9oqx6yr66cva4ro6l8m63r` FOREIGN KEY (`CAR_ID`) REFERENCES `cars` (`CAR_ID`))
ERROR: org.hibernate.internal.ExceptionMapperStandardImpl - HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]
ERROR: com.app.cars.controller.AdminController - Exception during deleting car due to could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
无法更改表格属性和设计。因此,需要通过修复实体模型来消除此错误。
答案 0 :(得分:1)
您的实体模型不会将删除级联到Driver
,然后再级联到Penalty
,因此数据库会抛出约束违规错误。该模型应如下:
@Entity
class Car {
@OneToMany(cascade = CascadeType.ALL, mappedBy = "car", orphanRemoval = true)
private Set<Driver> drivers;
...
}
@Entity
class Driver {
@ManyToOne
private Car car;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "driver", orphanRemoval = true)
private Set<Penalty> penalties;
...
}
@Entity
class Penalty {
@ManyToOne
private Driver driver;
...
}