删除时出现ConstraintViolationException

时间:2018-12-21 11:46:59

标签: java spring spring-data-jpa

当我运行GET Http方法localhost:8080/api/empl/drivers/id=1时,我会得到json:

{
    "pesel": "240028313144621540785598931",
    "firstName": "Janusz",
    "lastName": "Nosacz",
    "login": "user2",
    "email": "driver@example.com",
    "isActive": null,
    "userRole": "DRIVER",
    "active": null,
    "id": 1
}

没关系,bu,当我想使用DELETE Http方法:localhost:8080/api/empl/drivers/id=1删除id时,我得到了错误:"could not execute statement; SQL [n/a]; constraint [\"FKDPOR9OHOV2F3OPTWE7TWE49TT: DBO.VEHICLE FOREIGN KEY(DRIVER_ID) REFERENCES DBO.DRIVER(ID) (1)\"; SQL statement:\ndelete from driver where id=? [23503-197]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement",

我跑步时也会发生同样的事情

Driver employee0 = new Driver("94112757255", "Janusz", "Nosacz");
employee0.setUser(user2);
driverRepo.save(employee0);
driverRepo.deleteById(1L);

我认为这是由于与ID = 1的驾驶员相关联的Vehicle所致。 (驾驶员与车辆没有关联。)

@Entity
public class Vehicle {

// ...

    @OneToOne(cascade=CascadeType.REFRESH)
    private Driver driver;

// ...

}

// ...

Vehicle vehicle0 = new Vehicle("1FTEF27L2VND02190");
    vehicle0.setDriver(employee0);
    vehicleRepo.save(vehicle0);

这就是我在驱动程序上进行删除的方法:

@Service
public class DriverServiceImpl implements DriverService {

    private final DriverRepo driverRepo;

// ...

    @Override
    public void deleteDriver(Long id) {
        driverRepo.deleteById(id);
    }
}

根据在stackoverflow.com上发现的相似问题,我尝试使用cascade.ALL和orphonalremoval = true,但没有帮助。

任何想法如何解决?我想我必须删除对车辆ID为1的驾驶员的引用,但这是有问题的...
 这是应用程序的完整代码:https://github.com/woblak/deliverp

1 个答案:

答案 0 :(得分:0)

这是解决方案:

class Driver {


@Id
Long id;

@OneToOne(mappedBy="driver")
 Vehicle vehicle;

@PreRemove
public void preRemove() {
    vehicle.setDriver(null);
}

// getters and setters...


}

class Vehicle{

    @Id
    Long id;

    @OneToOne
    Driver driver;

    // getters and setters
}

关键是使双向关联并添加带有@PreRemove批注的添加方法,该批注将在删除对象之前运行。