1

Let's say that I have:

class Car {
    ...
    @OneToMany(mappedBy = "wheel", fetch = FetchType.LAZY)
    @Cascade(org.hibernate.annotations.CascadeType.ALL)
    Set<Wheel> wheels;

}

class Wheel {
    ...
    @ManyToOne(fetch = FetchType.LAZY)
    Car car

}

I have this code (spring data, wheelRepository extends CrudRepository) to delete a Wheel:

wheelRepository.delete(wheel);

The code does not delete the wheel and does not throw any exception. Looking at the sql log, there is no "delete" statement.

I finally found a the problem: I have a car with a wheel set containing the wheel.

Doing this will solve the issue:

car.getWheels().remove(wheel);
wheelRepository.delete(wheel);

But is it possible to avoid the first line: when I delete a wheel, I want the wheel to be removed from its car automatically?

Another question: is it possible by default to throw an exception instead of having a "silently non-delete"?

Thanks!

3 Answers 3

1

What you want is not quite possible. When you call wheelRepository.delete(wheel) you essentially ask to remove the wheel from the database. But this cannot remove an instance wheel from all other places in your running application where this instance is now referenced. Such as car.wheels. So this instance will continue to live. Thus, it cannot be removed from the database. If you want to remove a wheel you have first to remove it from all cars that use that wheel. Exactly like in real life :)

Sign up to request clarification or add additional context in comments.

Comments

0

You can define your wheels field like this:

@OneToMany(mappedBy = "wheel", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
Set<Wheel> wheels;

This will ensure that when you remove the Wheel entity the Car entities that became orphans because of it will get removed as well.

1 Comment

But I don't want to remove the car, just want to remove one wheel :-)
0

You are trying to delete Wheel which contains Car

But for Car you have not specified CascadeType.

So while deleting Wheel it does ntg to Car.

@ManyToOne(cascade = CascadeType.ALL) 

Add this to Car inside Wheel and try.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.