我的 Comment
实体是自连接的,它有一个 subComment
集。
@Entity
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String id;
@OneToMany(mappedBy = "parentComment", cascade = CascadeType.ALL)
private Set<Comment> subComments = new HashSet<>();
@ManyToOne
@JoinColumn(referencedColumnName = "id")
private Comment parentComment;
在我的addComment
方法中
public ResponseEntity<Comment> 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);
}
当我试图建立反向关系(拥有方)时,
comment.setParentComment(parent);
导致错误
comment.setParentComment(parent);
导致错误:java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
完整评论实体类
@OneToMany(mappedBy = "parentComment", cascade = CascadeType.ALL)
private Set<Comment> subComments = new HashSet<>();
@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<Comment> getSubComments() {
return subComments;
}
public void setSubComments(Set<Comment> 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;
}
最佳答案
@ManyToOne
@JoinColumn(referencedColumnName = "id")
@JsonBackReference
private Comment parentComment;
我添加了 @JsonBackReference 解决了 java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
错误。父 Comment
也可以看到 subComments
集。
关于java - Spring Data 和 JPA 中的递归关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50554246/