📘 대댓글 구현하기: 설계부터 구현까지 완전 정리


✅ 1. 대댓글이란?

💬 예시 구조

댓글1
 └─ 대댓글1-1
 └─ 대댓글1-2
댓글2
 └─ 대댓글2-1


✅ 2. DB 설계: Self Join 방식

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)
);


✅ 3. JPA 엔티티 설계

@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을 통해 트리 구조의 재귀 관계 표현 가능


✅ 4. 저장 로직 예시

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이면 일반 댓글, 있으면 대댓글로 처리