Specify order in which hibernate deletes related objects


#1

If I have the following class and I want to delete a car. Can I specify in hibernate that it first need
to remove all the rims and than remove all the weels? How does hibernate decide the order?

public class Car{

    @Column(name = "name", nullable = false)
    private String name;

    @OneToMany(mappedBy = "Car", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Wheel> wheels= new ArrayList<>();

    @OneToMany(mappedBy = "Car", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Rim> rims= new ArrayList<>();

    ....
}

#2

You cannot control the order of cascade via some annotation, but you can do it in your code like this:

car.removeAllRims();

entityManager.flush:

entityManager.remove(car);

During cascade, the operation is cascaded to all properties in the same order they were registered during bootstrap.