In my application, a hibernate operation goes like this. The application updates a parent entity with new values from the request and deletes all the existing (previously insert
instead of setChilds
use addAll
,
from this,
parent.getChilds().clear();
parent.setChilds(newChilds);
to
parent.getChilds().clear();
parent.getChilds().addAll(newChilds);
It worked for me.
Instead of setting the new child entities to my parent object, I have used addAll method to add the new child entities.
parent.getChildren().clear();
parent.getChildren().addAll(newChildrenList);
@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY,
cascade = CascadeType.ALL, orphanRemoval = true)
public Set<Children> getChildren() {
return this.children;
}
Your last snippet of Java code doesn't compile. I guess it looks like
parent.getChilds().clear(); // note: you should name it children rather than childs
parent.setChilds(someNewSetOfChildren):
Don't do the last instruction. Instead of replacing the set by another one, clear the set and add the new children to the cleared set:
parent.clearChildren();
parent.addChildren(someNewSetOfChildren);
where the methods are defined as:
public void clearChildren() {
this.children.clear();
}
public void addChildren(Collection<Child> children) {
this.children.addAll(children);
}
The setChildren method should be removed completely, or it should be replaced with the following implementation:
public void setChildren(Collection<Child> children) {
this.children.clear();
this.children.addAll(children);
}
I faced the same issue and get it solved as follows:
1- add {CascadeType.ALL}, orphanRemoval=true in all @OneToMany annotations in all entity Childs of that element.
2- Check the hashcode() and equalls() of those entities, some times they have erros
3- Don't use parent.setChilds(newChilds);
as the engine will ask for missing the reference to the childs, but use instead use
parent.getChilds().clear();
parent.getChilds().add(Child);
or
parent.getChilds().addAll(Childs);
Those steps solved my issue after 4 Hours of research
it change works !
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "user_id")
private List<Role> roles;