Everyday Dev System

myBlog : 튜터님 피드백 반영 2 본문

내배캠 주요 학습/Spring 숙련

myBlog : 튜터님 피드백 반영 2

chaeyoung- 2023. 7. 12. 14:14

 

 

아래와 같이 피드백을 받았습니다.

 

 

 

    public List<PostResponseDto> getPostList() {
        List<Post> postList = postRepository.findAllByOrderByCreatedAtDesc();
        List<PostResponseDto> responseDtoList = new ArrayList<>();

        for (Post post : postList) {
            post.setCommentList(commentRepository.findAllByPostIdOrderByCreatedAtDesc(post.getId()));
            responseDtoList.add(new PostResponseDto(post));
        }
        return responseDtoList;
    }

먼저,  PostService 클래스 내부에서 전체 게시글을 조회하는 메서드 코드입니다.

 

 

DB에서 조회해 온 post 객체에 setCommentList를 할 필요가 없다는 말씀이였습니다.

post.setCommentList(commentRepository.findAllByPostIdOrderByCreatedAtDesc(post.getId()));

제가 해당 코드를 작성한 이유는, 댓글을 작성일자 순으로 정렬하기 위함이였습니다.

그렇지만, Entity는 DB에 연동하여 DB에 데이터를 조작할 때 사용하는 클래스입니다.
하여 Entity가 아닌 Dto에서 데이터를 정렬하여 Client에 반환하는 것이 맞습니다.

처음에는 PostResponseDto 클래스 내부에 생성자 메서드에서 처리하려고 하였으나,
다른 메서드에서도 다량의 에러가 발생하여, set 메서드를 따로 만들어서 정렬한
댓글 List를 설정해주는 방식을 택하였습니다.

결과적으로 아래와 같이 service 코드와 Dto 코드를 아래와 같이 수정하여 피드백을 반영하였습니다.
기능도 정상적으로 잘 작동이 되었습니다.

 

PostResponseDto.java 

package com.sparta.myblog.dto;

import com.sparta.myblog.entity.Comment;
import com.sparta.myblog.entity.Post;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Getter
@Setter
public class PostResponseDto {

    private Long id;
    private String title;
    private String username;
    private String contents;
    private LocalDateTime createdAt;
    private LocalDateTime modifiedAt;
    private Long likeCnt;
    private List<CommentResponseDto> commentResponseDtoList;

    public PostResponseDto(Post post) {
        this.id = post.getId();
        this.title = post.getTitle();
        this.username = post.getUser().getUsername();
        this.contents = post.getContents();
        this.createdAt = post.getCreatedAt();
        this.modifiedAt = post.getModifiedAt();
        this.likeCnt = post.getLikeCount();
        if(post.getCommentList().size()>0) {
            this.commentResponseDtoList = new ArrayList<>();
            for (Comment comment : post.getCommentList()) {
                this.commentResponseDtoList.add(new CommentResponseDto(comment));
            }
        }// end of the if()
    }// end of constructor method()

    public void setCommentResponseDtoList(List<Comment> sortedCommentList) {
        this.getCommentResponseDtoList().clear();
        for (Comment comment : sortedCommentList) {
            this.commentResponseDtoList.add(new CommentResponseDto(comment));
        }
    }
 }

 

 

PostService.java

package com.sparta.myblog.service;

import com.sparta.myblog.dto.PostRequestDto;
import com.sparta.myblog.dto.PostResponseDto;
import com.sparta.myblog.entity.Comment;
import com.sparta.myblog.entity.Post;
import com.sparta.myblog.entity.User;
import com.sparta.myblog.entity.UserRoleEnum;
import com.sparta.myblog.repository.CommentRepository;
import com.sparta.myblog.repository.PostRepository;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
@RequiredArgsConstructor
public class PostService {

    private final PostRepository postRepository;
    private final CommentRepository commentRepository;


    // 1. 전체 게시글 모두 조회
    public List<PostResponseDto> getPostList() {
        List<Post> postList = postRepository.findAllByOrderByCreatedAtDesc();
        List<PostResponseDto> responseDtoList = new ArrayList<>();

        for (Post post : postList) {
            PostResponseDto postResponseDto = new PostResponseDto(post);
            if(postResponseDto.getCommentResponseDtoList().size()>0) { // 해당 게시글에 댓글이 있을 경우 내림차순 정렬
                List<Comment> sortedCommentList = commentRepository.findAllByPostIdOrderByCreatedAtDesc(post.getId());
                postResponseDto.setCommentResponseDtoList(sortedCommentList);
            }
            responseDtoList.add(postResponseDto);
        }
        return responseDtoList;
    }


    // 2. 선택한 게시글 한개 조회
    public PostResponseDto getPost(Long id) {
        Post post = findPost(id);
        PostResponseDto postResponseDto = new PostResponseDto(post);
        if(postResponseDto.getCommentResponseDtoList().size()>0) { // 해당 게시글에 댓글이 있을 경우 내림차순 정렬
            List<Comment> sortedCommentList  = commentRepository.findAllByPostIdOrderByCreatedAtDesc(post.getId());
            postResponseDto.setCommentResponseDtoList(sortedCommentList);
        }
        return postResponseDto;
    }


}

 

 

 

 


references : 

https://github.com/Chaeyounglim/myBlog/commit/4d0c9b1b69d8f163cbe03fe16c75104ec9015019

아래는 제가 피드백을 반영한 후에 작성한 github commit 내용입니다.

REFACTOR : code refactoring in all or one post show.


피드백 : Post Entity 객체에 commentListset할 필요가 없다고 하셨습니다.
이유는, Post Entity 자체에서 Comment와의 연관관계를 맺어주었기 때문에 post를 조회해올 때 commentjPA에서 조회해온다고 합니다.

해결방법 :
PostService 클래스 내에 getPostList() 메서드와 getPost() 메서드를 수정하였습니다.

그러나, 이를 없애면 댓글을 작성일자 기준으로 내림차순하여 출력할 수가 없기에,
DB의 정보를 수정하는 Entity 가 아닌 Dto 클래스 내부에서 설정하도록 하였습니다.

먼저 service단에서 댓글을 내림차순으로 객체 list에 받아오고,
이를 setCommentResponseDtoList() 메서드에 매개변수로 넘겨주어
set 해준 후에 return 하였습니다.