Hibernate / Spring Data上的级联删除

时间:2016-08-23 22:01:10

标签: java hibernate jpa spring-data spring-data-jpa

我有以下实体:

@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时删除CarcarRepository.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

无法更改表格属性和设计。因此,需要通过修复实体模型来消除此错误。

1 个答案:

答案 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;

  ...
}