I have two entities: Comment, and SubComment. A Comment can have multiple SubComments. I'm trying to establish a one to many/many to one bidirectional relationship with Hibernate.
I do not know what is wrong. Both of the tables seem to have been created correctly in PSQL.
Comment.java
import javax.persistence.*;
import java.util.Set;
@Entity
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column
private String text;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "comment")
private Set<SubComment> subComment;
public …Run Code Online (Sandbox Code Playgroud) 我的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;
Run Code Online (Sandbox Code Playgroud)
在我的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);
}
Run Code Online (Sandbox Code Playgroud)
当我尝试建立反向关系(拥有方)时,
comment.setParentComment(parent);导致错误
comment.setParentComment(parent); 导致错误: …