Spring 게시판 6 - 조회수

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

Spring실습

목록 보기
7/40

24/12/31(화)

게시판 만들기 추가기능

조회수 만들기

<나의 고민>
❓ 조회수는 어디에 설치하면 될까?
-> 조회수는 게시글을 눌렀을 때 올라간다 : Post
❓조회수를 count하는 함수도 필요하다.
-> 조회하는 부분을 눌렀을 때, count해주기만 하면 된다.


조회수 변수

post에서 관리하기 때문에 post에 int count 변수를 달아준다.

 private int viewCount = 0;
 
public int getViewCount() {
        return viewCount;
    }

Getter는 항상 달아준다.

조회할 때 올라가니까, 조회버튼 누르는 곳으로 이동한다. (controller)

//조회
    @GetMapping("/posts/{postId}")
    public PostCommentResponse getPost(@PathVariable Long postId){
        return postService.getPostId(postId);
    }

조회할때 getPostId로 이동하니까 service에 있는 저 함수로 간다.

@Transactional
    //조회
    public PostResponse getPostId(Long postId) {
        Post post = postRepository.findById(postId).orElseThrow();
        post.countView();
        return new PostResponse(post.getTitle(), post.getContent(), postId, post.getCreatedAt());
    }

postId를 찾고, 찾았을 때 count를 한다.
service에서 너무 많은 일을 하게 하지 말고 역할을 분배해두기 위해 countView()라는 함수를 post안에 만들어둔다.

  public void countView() {
        this.viewCount = viewCount + 1;
    }

count는 1씩 올라가게 한다.

이렇게하면 조회수가 볼 때마다 올라간다.


게시글에 달린 댓글 개수 보여주기

<나의 생각>
❓ 댓글을 count해주는 변수는 어디에 넣을 것인가?
-> Comment? vs post?
댓글을 쓰는 거니까 comment?
❓ 댓글 개수니까, 댓글을 하나 쓸 때마다 count를 해주면 되지 않을까?
: 댓글을 생성할 때마다 count를 해주면 되겠다.
❓ 게시글을 조회할 때 count된 댓글 수를 반환해야한다.
-> post에도 댓글의 count를 가져와야한다.

Comment의 변수를 넣었을 때

private int viewCommentCount = 0;

public int getViewCommentCount() {
        return viewCommentCount;
    }

service수정

public CommentResponse save(CommentRequest commentRequest) {
      Post post = postRepository.findById(commentRequest.postId()).orElseThrow();
      post.incrementCommentCount();
      Comment save = commentRepository.save(
              new Comment(
                      commentRequest.content(),
                      commentRequest.author(),
                      commentRequest.createdAt(),
                      post));

      return new CommentResponse(save.getId(), save.getContent(), save.getAuthor(), save.getCreatedAt());
  }

🧐 내가 만난 문제점
댓글을 만들 땐 postId가 필요한다. postId를 찾고 나면 Post로 반환이 된다. 그럼 post안에 count를 해주는 함수가 필요하다. 그러면 viewCommentCount도 post로 옮겨줘야한다.

Post로 이동시킨다.

//post
private int viewCommentCount = 0;

public int getViewCommentCount() {
        return viewCommentCount;
    }
public void incrementCommentCount() {
        this.viewCommentCount = viewCommentCount + 1;
    }

이렇게 해주면 댓글을 만들 때마다 count를 하나씩 해주게 된다.

그럼 게시글을 조회할 때 count된 댓글 수 전체를 반환하면 된다.
먼저, 특정 게시글의 댓글 수를 응답으로 보내는 DTO를 새로 하나 만든다.

public record PostCommentResponse(
        String title,
        String content,
        Long id,
        String createdAt,
        int commentCount
) {
}

이 DTO로 반환해주는 것으로 조회함수를 만든다.
controller수정

 //조회
    @GetMapping("/posts/{postId}")
    public PostCommentResponse getPost(@PathVariable Long postId){
        return postService.getPostId(postId);
    }

Service수정

@Transactional
    //조회
    public PostCommentResponse getPostId(Long postId) {
        Post post = postRepository.findById(postId).orElseThrow();
        post.countView();
        return new PostCommentResponse(
                post.getTitle(),
                post.getContent(),
                postId,
                post.getCreatedAt(),
                commentRepository.countByPostId(postId));
    }

commentRepository.countByPostId(postId) JPA쿼리 메서드로 count를 해주는 함수를 만든다.

이렇게하면 게시글 조회할때 댓글 개수도 반환해준다.


😐 느낀점

API를 처음부터 같이 만들지 않으면, 수정하는게 하나가 생겨도 어렵다는 걸 좀 느낀다.
하지만 수정하는 상황은 계속적으로 이루어지기 때문에, 코드를 수정하면서 바꿔가는 연습도 필요하다.

0개의 댓글