SpringBoot Project

[SpringBoot] 게시판 게시물 조회수 기능

꿈꾸는야오옹 2023. 1. 28. 19:47

게시물을 클릭하면 조회수가 증가하는 쿼리를 추가해 주려고 한다.

 

우선 엔티티에 조회수 컬럼을 넣어주고

private int readCount;
//BoardEntity 에 있는 조회수 컬럼

 

그리고 이제 repository에 조회수 증가 쿼리를 작성해주었다.

@Modifying
@Query("update BoardEntity b set b.readCount = b.readCount +1 where b.bno = :bno") //entity 의 readCount를 업데이트하는 쿼리
int updateReadCount(@Param("bno")Long bno);

나같은 경우는 @Param("bno") 를 추가하지 않으면 실행이 되지 않아 추가를 해주었다.

 

 

그리고 service process에 아래와 같이 메소드를 구현하였다.

@Transactional
public int updateReadCount(Long bno) {
    return repository.updateReadCount(bno);
}

 

 

그리고 이 메소드는 contoller에서 사용해주었다. 게시물을 클릭하면 게시물 detail페이지로 이동하며 조회수가 업데이트 된다.

//공지사항 상세 페이지
@GetMapping("/notice-boards/{bno}")
public String detail(@PathVariable long bno, Model model) {
   
    service.updateReadCount(bno);  //조회수(레포지토리에 쿼리 추가 후)
    
    service.sendDetail(bno, model);
    serv.findAll(model); // 댓글 목록
    return "board/noticeDetail";
}

끝!!