Spring 게시판 5 - 댓글

춤인형의 개발일지·2025년 1월 1일

Spring실습

목록 보기
6/40

24/12/30(월)

게시판 만들기

댓글 만들기 CRUD

1. DTO설계
API을 보고, 그에 맞는 Request, Response를 작성해야한다.

//Request
public record CommentRequest(
        String content,
        String author,
        String createdAt,
        Long postId
) {
}
//Response
public record CommentResponse(
        Long id,
        String content,
        String author,
        String createdAt
) {
}

2. Entity 설계

@Entity
public class Comment {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    //1. 내용은 중복될 수 있음
    private String content;
    private String author;
    private String createdAt;

    @ManyToOne
    private Post post;

    public Comment(String content, String author, String createdAt, Post post) {
        this.content = content;
        this.author = author;
        this.createdAt = createdAt;
        this.post = post;
    }

    public Comment() {
    }


    public Long getId() {
        return id;
    }

    public String getContent() {
        return content;
    }

    public String getAuthor() {
        return author;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    public Comment(Post post) {
        this.post = post;
    }
}
  • id
    id는 절대 중복되면 안되기 때문에 id값을 새로 만들어 id를 넣어준다.
  • @ManyToOne
    참조한다 라는 의미로 달아줘야한다. 내가 데이터베이스(DB)에 post라는 칼럼을 넣을게 아니기 때문에 참조이다.

3. Controller구현

RestController
public class CommentController {
    private CommentService commentService;

    public CommentController(CommentService commentService) {
        this.commentService = commentService;
    }

    //조회
    @GetMapping("/comments")
    public List<CommentResponse> read(@RequestParam Long postId){
        return commentService.read(postId);
    }

    @PostMapping("/comments")
    public CommentResponse create(@RequestBody CommentRequest commentRequest){
        return commentService.save(commentRequest);
    }
}

Repository를 사용하려면 댓글 Respository가 있어야한다.

public interface CommentRepository extends JpaRepository<Comment, Long> {
}

service마저 구현

  • 조회
    댓글도 게시글이 없는 댓글은 존재하지 않는다. 따라서 관계가 1:N 관계이다.
    조회할때도 특정 게시글이 있는지 없는지를 파악해야한다.
    그럴려면 postId를 알아야하는데 CommentRepository에는 post에 대한 정보가 없으니까 넣어준다.

Repository수정

public interface CommentRepository extends JpaRepository<Comment, Long> {
    List<Comment> findByPostId(Long postId);
}

이걸 토대로 postId값을 찾아서 output값을 반환해준다.

@Service
public class CommentService {
    private CommentRepository commentRepository;
    private final PostRepository postRepository;

    public CommentService(CommentRepository commentRepository, PostRepository postRepository) {
        this.commentRepository = commentRepository;
        this.postRepository = postRepository;
    }

    public List<CommentResponse> read(Long postId) {
        //postId를 찾아서 그 아이디에 있는 comment를 찾아라
        List<Comment> byPostId = commentRepository.findByPostId(postId);
		return byPostId.stream().map(
                comment -> new CommentResponse(
                        comment.getId(),
                        comment.getContent(),
                        comment.getAuthor(),
                        comment.getAuthor())).toList();
    }
  • 저장
    postId값을 저장해줘야 댓글이 달릴 때 어느 게시물에 달린 댓글인지 알 수 있다.
    따라서 저장할 때 postId도 저장해준다.
    public CommentResponse save(CommentRequest commentRequest) {
        Post post = postRepository.findById(commentRequest.postId()).orElseThrow();
        Comment save = commentRepository.save(
                new Comment(
                        commentRequest.content(),
                        commentRequest.author(),
                        commentRequest.createdAt(),
                        post));
        return new CommentResponse(save.getId(), save.getContent(), save.getAuthor(), save.getCreatedAt());
    }
}

이렇게하면 댓글도 완료!


😐 느낀점

잊지 않아야하는것은 관계를 맺은 id값을 저장할 때, 만들 때, 읽어올 때 등등 사용된다. 
언제 어떻게 사용되는지 파악해서 적절하게 사용하는 연습이 필요하다.

0개의 댓글