댓글1
└─ 대댓글1-1
└─ 대댓글1-2
댓글2
└─ 대댓글2-1
CREATE TABLE comment (
id BIGINT PRIMARY KEY,
content TEXT,
parent_id BIGINT, -- 부모 댓글을 가리키는 외래키
post_id BIGINT,
FOREIGN KEY (parent_id) REFERENCES comment(id),
FOREIGN KEY (post_id) REFERENCES post(id)
);
parent_id가 NULL이면 최상위 댓글parent_id가 존재하면 대댓글@Entity
public class Comment {
@Id
@GeneratedValue
private Long id;
private String content;
// 연관 게시글
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "post_id")
private Post post;
// 대댓글 관계
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
private Comment parent;
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Comment> children = new ArrayList<>();
// 작성자, 생성일 등 추가 가능
}
💡 parent와 children을 통해 트리 구조의 재귀 관계 표현 가능
public Comment createComment(Long postId, String content, Long parentId) {
Post post = postRepository.findById(postId).orElseThrow();
Comment parent = parentId != null ? commentRepository.findById(parentId).orElse(null) : null;
Comment comment = Comment.builder()
.post(post)
.parent(parent)
.content(content)
.build();
return commentRepository.save(comment);
}
🔑 parentId가 null이면 일반 댓글, 있으면 대댓글로 처리