스프링 부트, 확장!

준비중..

스프링 부트, 확장!

댓글 기능 및 소셜 로그인!

26 댓글 목록 보기

# 댓글 목록 보기 ## 미션 --- 게시글에 달린 모든 댓글을 조회하시오. ![클라우드스터딩-스프링부트-댓글-목록-조회](https://i.imgur.com/xL732he.png) ## 개념 --- #### ⭐️ 기본키(PK)와 참조키(FK) 일반적으로 한 게시글에는 여러 댓글이 달린다. 이를 참고하여 아래의 질문에 답해보자. ![클라우드스터딩](https://i.imgur.com/d6Gh6ba.png) #### ⭐️ 테이블 조인 위에서 작성한 정답을 기준하여, 데이터를 가져와보자. 1번 게시글과 그 모든 댓글을 가져오려면 어떤 SQL을 작성해야 할까? 이를 위한 개념이 바로 테이블 조인(JOIN)이다. JOIN 문법을 사용하면, 공통점을 기준으로 합쳐진 임시 테이블을 만들 수 있다. ![클라우드스터딩-스프링-부트-테이블-조인](https://i.imgur.com/PdR7775.png) ## 튜토리얼 --- #### ⭐️ 뷰 페이지 1) 댓글 목록 추가: "comments/_comments.mustache" ``` <div class="card" id="comments"> <div class="card-body"> <!-- 댓글 작성 창 --> <a href="#comment"></a> <form> <div class="form-group"> <label>댓글 작성</label> <textarea class="form-control" id="comment-content" rows="3"></textarea> </div> <input type="hidden" id="comment-author" value="익명"> <button type="button" class="btn btn-primary" id="comment-create-btn">제출</button> </form> <!-- 댓글 목록 --> <ul class="list-unstyled"> {{#comments}} <li class="media mt-4"> <img src="https://api.adorable.io/avatars/64/{{author}}.png" class="mr-3" alt="avata"> <div class="media-body"> <h5 class="mt-0 mb-1">{{author}}</h5> <p>{{content}}</p> </div> </li> {{/comments}} </ul> </div> </div> <Script src="/js/app/comment.js"></script> ``` #### ⭐️ 컨트롤러 2) 댓글 데이터 뷰로 전달: "controller/ArticleController#show" ``` @GetMapping("/articles/{id}") public String show(@PathVariable Long id, Model model) { Article article = articleRepository.findById(id) .orElseThrow( // article이 없을 시, 에러 발생! () -> new IllegalArgumentException("해당 Article이 없습니다.") ); log.info(article.toString()); // 데이터를 뷰 페이지로 전달 model.addAttribute("article", article); model.addAttribute("comments", article.getComments()); return "articles/show"; } ``` #### ⭐️ 확인하기 3) 댓글 작성 후 확인 ![클라우드스터딩-스프링부트-댓글-조회-성공](https://i.imgur.com/Nbc2NiQ.png) ## 훈련하기 --- 위 "진행 8)" 에서 하나의 댓글 더 작성하면, 에러가 발생한다. ![클라우드스터딩-스프링부트-toString-스택-오버-플로우-에러](https://i.imgur.com/7qjsZDC.png) 이를 해결하기 위해서는, 엔티티 클래스 "entity/Article"의 toString() 메소드를 재정의 해야 한다. ``` // @ToString 애노테이션 제거 @Getter @NoArgsConstructor @Entity public class Article extends BaseTime { ... @Override // toString() 메소드를 직접 오버라이딩(재정의) 함! public String toString() { return "Article{" + "id=" + id + ", title='" + title + '\'' + ", content='" + content + '\'' + ", comments=" + (comments == null ? null : comments.size()) + '}'; } } ``` - 위 에러의 발생한 원인을 분석하고, 어떻게 해결된 것인지 설명하시오. (힌트: "JPA 양방향 순환 참조") - DB에서 특정 게시글의 모든 댓글을 얻는 JOIN 문법을 작성하고, 그 결과를 확인하시오. ## 면접 준비 --- - DB에서 "테이블 조인"은 무엇? 왜씀? - "스택 오버 플로우"란 무엇? 언제 발생?