title: Recursive relationship in Spring Data and JPA?
body: <p>My <code>Comment</code> entity is self-joined that has a <code>subComment</code> set.</p>
  
  <pre><code>@Entity
  public class Comment {
  
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private String id;
  
  @OneToMany(mappedBy = "parentComment", cascade = CascadeType.ALL)
  private Set&lt;Comment&gt; subComments = new HashSet&lt;&gt;();
  
  @ManyToOne
  @JoinColumn(referencedColumnName = "id")
  private Comment parentComment;
  </code></pre>
  
  <p>Here in my <code>addComment</code> method</p>
  
  <pre><code>public ResponseEntity&lt;Comment&gt; addComment(Comment comment) {
      Comment currComment = commentRepository.save(comment);
      if (currComment.getParentId() != null) {
          Comment parent = commentRepository.findById(currComment.getParentId()).orElse(null);
          if (parent != null) {
              parent.addSubComment(currComment);
              currComment.setParentId(parent.getId());
              currComment.setParentComment(parent);
              commentRepository.save(parent);
          }
      }
      Comment responseComment = commentRepository.save(currComment);
      return ResponseEntity.ok(responseComment);
  }
  </code></pre>
  
  <p>When I tried to establish the reverse relationship (owning side),
  <code>comment.setParentComment(parent);</code> causes the error</p>
  
  <p><code>comment.setParentComment(parent);</code> is causing an error: <code>java.lang.IllegalStateException: Cannot call sendError() after the response has been committed</code></p>
  
  <p>Full Comment entity class</p>
  
  <pre><code>@OneToMany(mappedBy = "parentComment", cascade = CascadeType.ALL)
  private Set&lt;Comment&gt; subComments = new HashSet&lt;&gt;();
  
  @ManyToOne
  @JoinColumn(referencedColumnName = "id")
  private Comment parentComment;
  
  private boolean isParent;
  private String parentId;
  
  public String getParentId() {
      return parentId;
  }
  
  public void setParentId(String parentId) {
      this.parentId = parentId;
  }
  
  public Set&lt;Comment&gt; getSubComments() {
      return subComments;
  }
  
  public void setSubComments(Set&lt;Comment&gt; subComments) {
      this.subComments = subComments;
  }
  
  public Comment addSubComment(Comment comment) {
      this.subComments.add(comment);
      return this;
  }
  
  public Comment getParentComment() {
      return parentComment;
  }
  
  public void setParentComment(Comment parentComment) {
      this.parentComment = parentComment;
  }
  
  public boolean getIsParent() {
      return isParent;
  }
  
  public void setIsParent(boolean isParent) {
      this.isParent = isParent;
  }
  </code></pre>