스파르타 내배캠

[TIL] #26. entity 연결

saemsaem 2024. 5. 28. 20:24


 

 [ 개인과제 ] 

2단계 : 댓글 등록

Entity를 연결하는 방법
  1. DB에 내가 원하는 schedule이 있는지 확인하고
  2. 있다면 연관관계를 맺고 (+예외처리)
  3. 저장한다.


// CommentController
@PostMapping("/board/{boardId}/comments")
public CommentResponseDto createComment(@RequestBody CommentRequestDto requestDto, @PathVariable Long boardId) {
    return commentService.createComment(requestDto, boardId);
}

파라미터에서 @PathVariable을 사용하여 boardId를 받아온다.

// CommentService
public CommentResponseDto createComment(CommentRequestDto commentRequestDto, Long boardId) {
    Board board = boardService.findBoard(boardId); // DB에 있는지 먼저 확인
    Comment comment = new Comment(commentRequestDto, board); // 있으면 -> 연관관계 맺기

    // 예외처리
    if (comment.getContent().isEmpty()) { // 댓글 내용이 비어 있는 경우
        throw new IllegalArgumentException("댓글 내용을 작성해주세요");
    }
    else if (comment.getBoard() == null) { // 일정이 DB에 저장되지 않은 경우
        throw new IllegalArgumentException("등록된 일정을 선택해주세요.");
    }

    commentRepository.save(comment); // 저장

    return new CommentResponseDto(comment);
}

먼저 boardId로 board가 DB에 저장되어 있는 값인지 찾아본다. 
원래는 CommentService에 BoardService를 선언하지 않는 것이 원칙이지만, 이번 과제에서는 일단 선언해서 사용한다. 

board가 존재한다면, 연관관계를 맺어 새로운 comment 객체를 생성한다. 

commentRepository에 저장하기 전 예외처리를 한다. 

// Comment
public Comment(CommentRequestDto requestDto, Board board) {
    this.content = requestDto.getContent();
    this.userId = requestDto.getUserId();
    this.board = board;
}

Comment Entity의 constructor에 board가 추가되어야 한다.