nlimits
nlimits

Reputation: 113

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).

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.

Upvotes: 1

Views: 6219

Answers (1)

manish
manish

Reputation: 20135

Your entity model does not cascade deletes to Driver and then to Penalty, hence the database throws a constraint violation error. 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;

  ...
}

Upvotes: 3

Related Questions