life is egg
게시글마다 댓글조회하기. 본문
이제 게시글별로 댓글 조회 가능하다
게시글조회와 댓글조회를 각각 다른 API로 짰는데 그렇게 하는것보다 게시글조회시에 해당 게시글id에 맞는
댓글을 댓글저장소에서 id로 긁어오는 식으로 만들었다
그래서 일단 댓글과 포스트를 같이 주는 Dto를 하나 만듦..!
CommentAndPostResponseDto.java
package com.example.springpac.web.dto;
import com.example.springpac.domain.comment.entity.Comment;
import com.example.springpac.domain.posts.entity.Posts;
import lombok.Getter;
import java.util.ArrayList;
@Getter
public class CommentAndPostResponseDto {
private Long id;
private String title;
private String content;
private String author;
private ArrayList<Comment> comment;
public CommentAndPostResponseDto(Posts entity, ArrayList<Comment> commentList){
this.id = entity.getId();
this.title = entity.getTitle();
this.content = entity.getContent();
this.author = entity.getAuthor();
this.comment = commentList;
}
}
포스트id값은 컨트롤러단에서 @PathVariable 이용해서 가져온다 이 id값으로 각각의 레포에서 포스트와 댓글을 찾을것
이를 위해 PostsService.java 에있는 findById 메소드를 수정했다
public CommentAndPostResponseDto findById (Long id){ //여기서 추가해야할게 뭐냐 댓글을 가져오는거 추가시켜주면 되자나
Posts entity = postsRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("해당 게시글이 없습니다. id =" + id));
ArrayList<Comment> commentArrayList = commentRepository.findByPostIdOrderByCreatedDateDesc(id);
return new CommentAndPostResponseDto(entity,commentArrayList);
}
여기서 기존 자료형이 되어있던 PostResponseDto.java는 유지해서 post업데이트시 써먹어야한다
그러면 이제 IndexController.java는 동일하다 단지 저 Dto안에 해당id의 리스트가 담겨있을뿐
@GetMapping("/posts/see/{id}")
public String postsSee(@PathVariable Long id,Model model){
CommentAndPostResponseDto dto =postsService.findById(id);
model.addAttribute("see",dto);
return "post-see";
}
여기서"see"로 담았으니까 인식하려면 머스테치에도 {{see.dto의원하는값}} 이렇게 해서 알맞은 자리에 배치하면된다
<tbody id="tbody">
{{#see.comment}}
<tr>
<td>{{comment}}</td>
<td>{{author}}</td>
<td>{{modifiedDate}}</td>
<th><a>수정</a></th>
<th><a>삭제</a></th>
</tr>
{{/see.comment}}
</tbody>
{{#see.comment}}는 for문돌리는거와 유사한 문법이다
댓글은 잘 저장됨!
포스트맨에서도 각게시글마다 각사용자마다 알아서 잘 달린다
이러면 아직까지는 JPA 관계설정도 필요없다
업데이트는 상관없는데 이러면 게시글 삭제시 댓글도 아이디로 조회해서 삭제해야할듯하다..;;
그냥 내장지방같은 데이터...가 되면 안되겠니..
앞으로 남은.. 댓글 삭제/수정 .....음.. 게시글과 비슷하긴하지... .삭제버튼 누르면 ..? 해당 댓글의 아이디를 삭제하면 되자나그러면 삭제버튼에 해당 댓글의...id값을 심어놓고 이걸 json전송 dto에서 조회... 추가로 토큰으로 사용자조회 오.. 대박..
'개인공부 > 삽질' 카테고리의 다른 글
게시글 삭제 시 댓글 삭제 (2) | 2022.12.29 |
---|---|
댓글 삭제 수정 (0) | 2022.12.27 |
삽질 FE (0) | 2022.12.18 |
계좌번호 만들기 + 마스킹하기 (0) | 2022.11.26 |
투두두두두 (0) | 2022.11.06 |