0

I have the below JPA entities defined with bidirectional one-to-many mapping. I observed that delete SQL statement is fired when a comment is removed from a list on post(post.removeComment(...)) even without setting orphan removal = true or making the post reference "null" on the comment .

What is the significance of Orphan removal = true when trying to delete items from a collection in JPA as I see the deletion is working fine even without it.

@Entity(name = "Post")
@Table(name = "post")
public class Post {
 
    @Id
    @GeneratedValue
    private Long id;
 
    private String title;
 
    @OneToMany(
        mappedBy = "post",
        cascade = CascadeType.ALL
    )
    private List<PostComment> comments = new ArrayList<>();
 
    public Post addComment(PostComment comment) {
        comments.add(comment);
        comment.setPost(this);
        return this;
    }
 
    public Post removeComment(PostComment comment) {
        comments.remove(comment);
        return this;
    }
}
@Entity(name = "PostComment")
@Table(name = "post_comment")
public class PostComment {
 
    @Id
    @GeneratedValue
    private Long id;
 
    @ManyToOne(fetch = FetchType.LAZY)
    private Post post;
 
    private String review;
}
swathi manda
  • 101
  • 1
  • 7
  • Have you checked this article? https://vladmihalcea.com/orphanremoval-jpa-hibernate/ – artiomi Oct 13 '22 at 18:23
  • JPA manages your relationship tied to the owning entity. In this case, your removeComment method does absolutely nothing; you would need to null out the postComment.post reference for there to be any change in the database. This might be why when you call remove on a Post all postComments are deleted - they still reference the Post, are found by JPA and so the delete cascades over to them. If you see PostComment instances deleted simply by calling post.removeComment then you have set orphan removal somewhere else: overrides, maybe through xml, or an old class with that set is on the class path – Chris Oct 13 '22 at 18:50

0 Answers0