I have a relationship:
Parent {
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "parent")
private List<Child> children= new ArrayList<>();
}
Child {
@ManyToOne
private Parent parent;
}
I want to remove all children and add new ones. That's why I call:
List<Child> newChildren = Arrays.asList(firstChild, secondChild);
parent.getChildren().clear();
parent.getChildren().addAll(newChildren);
parentRepository.save(parent); - I'm using spring data
However I saw that when I call the above code twice (I have more complicated logic, but this is the simplest case how I was able to reproduce my problem) without calling flush()
method, Hibernate adds duplicate entries to the database (parent will have 4 children):
parent.getChildren().clear();
parent.getChildren().addAll(newChildren);
parentRepository.save(parent);
parent.getChildren().clear();
parent.getChildren().addAll(newChildren);
parentRepository.save(parent);
Replacing save
with saveAndFlush
fixes above code and causes that parent has only 2 children.
Why is it necessary to call flush method before deleting and inserting new children to the parent?