Video in progress
What can happen if you put `CascadeType.ALL` on the `@ManyToOne` side?
If you delete the child, the REMOVE cascade passes to the parent, and the parent entity is deleted. If it has other children, you get an FK error or, even worse, unexpected data loss. Cascade is normally set in the parent → child direction.
📖 Answer
I've seen code like this on one project:
@Entity
class Comment {
@ManyToOne(cascade = CascadeType.ALL)
private Post post;
}
A moderator deleted a single comment:
em.remove(comment);
Hibernate cascades and tries to delete the post too. If the post has other comments, you get an FK constraint error and the transaction fails. If the post → comments side also has CascadeType.ALL, the entire post is deleted along with all its comments.
Which cascade makes sense where:
PERSIST: new children are saved along with the parent. Natural on the@OneToManyside.MERGE: the children are merged along with a detached parent.REMOVE: only if the child has no meaning without the parent (a part inside an aggregate).DETACH,REFRESH: rarely needed.
On the @ManyToOne side I don't put any cascade. The "many" side, which points to a shared object, shouldn't manage that object's lifecycle: an Order doesn't delete the product, and a Comment doesn't delete the post.
A quick check: "If I delete the child, is it right for the parent to be deleted too?" If the answer is no, you don't need cascade REMOVE.
Sign up to mark studied questions and save your progress.