[英]Cascade delete on Hibernate/Spring Data
I have the following entities: 我有以下实体:
@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;
...
}
I would like all information from Driver
and Penalty
deleted when a Car
is deleted as carRepository.delete(car_id)
. 当将
Car
删除为carRepository.delete(car_id)
时,我希望删除来自Driver
和Penalty
所有信息。
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
Cannot make change in table attributes and design. 无法更改表属性和设计。 So, need to get rid of this error by fixing the entity model.
因此,需要通过修复实体模型来消除此错误。
Your entity model does not cascade deletes to Driver
and then to Penalty
, hence the database throws a constraint violation error. 您的实体模型不会将删除操作先级联删除到
Driver
,然后再级联到Penalty
,因此数据库将引发约束冲突错误。 The model should be as follows: 该模型应如下所示:
@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;
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.