You're missing a fundamental step in your code: You need to update the association's owning side. Missing that can cause these kinds of exceptions or prevent Hibernate from performing any update on the database.
And you might want to double-check your cascade operations. More about that at the end of this post.
Disclaimer: I wasn't able to reproduce the error message in my example project. Instead of the error, Hibernate quietly removed the child record from the database. But that might be a detail that depends on the Hibernate version and/or the surrounding code.
Managing bidirectional associations
Let's start with the most important part: You modeled a bidirectional association. When you use it in your business code, you always need to update both sides.
If you want to dive deeper into association mappings, I recommend studying my best association mapping articles.
In your example, the call of the child.setParent(newParent)
method is missing:
@Transactional
public void mapChildToNewParent() {
// Get existing child and remove it from existing parent
Parent existingParent = parentRepo.findById(1L);
Child existingChild = existingParent.getChildren().iterator().next();
existingParent.remove(existingChild);
// Create new parent and add existingChild in it
Parent newParent = new Parent();
Set<Child> childrens = new HashSet<Child>();
childrens.add(existingChild);
newParent.setChildren(childrens)
child.setParent(existingChild);
// Save modified parent entities
parentRepo.save(existingParent);
parentRepo.save(newParent);
}
Using cascading and orphanRemoval
You're using cascading and orphanRemoval in your mappings. These should only be used for pure parent-child associations in which the child depends on the parent. In these cases, having a cascade definition on both ends of the association is uncommon. You should double-check if you need the cascade definition on the Child.parent
attribute and if it provides the expected results.
If your parent has many children, cascading a removal operation might cause performance issues.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…