1. 조회수 기능 추가하기
1-1 Repository
public interface BoardRepository extends JpaRepository<Board, Long> {
@Modifying
@Query("update Board p set p.view = p.view + 1 where p.id = :id")
int updateView(Long id);
}
레파지토리에 쿼리문을 작성해주었다
여기서 눈에 띄는 건 @Modifying인데, 저 어노테이션을 왜 썼냐 하면..
@Query 어노테이션으로 작성된 변경, 삭제 쿼리 메서드를 사용할 때 필요하다
즉, 조회 쿼리를 제외하고, 데이터 변경이 일어나는 INSERT, UPDATE, DELETE에서 사용된다
예제 코드에서는 UPDATE를 사용했기에 붙여줬다
1-2 Service
@Transactional
public int updateView(Long id) {
return boardRepository.updateView(id);
}
서비스
1-3 Controller
@GetMapping("/")
public String index(Long id, Model model, @PageableDefault(size = 10, sort = "id", direction = Sort.Direction.DESC) Pageable pageable) {
model.addAttribute("view", boardService.updateView(id));
model.addAttribute("boardList", boardService.getBoardList(pageable));
model.addAttribute("previous", pageable.previousOrFirst().getPageNumber()); // 이전 버튼
model.addAttribute("next", pageable.next().getPageNumber()); // 다음 버튼
model.addAttribute("check", boardService.getListCheck(pageable)); // 마지막 글 체크
return "index";
}
이렇게 모델 객체에 담고 뷰 쪽에 뿌려주기만 하면 된다
간단하다
위에 코드에서는 제일 첫 줄에 작성한 코드가 조회수 코드이다 "view"
1-4 결과
메인화면에 조회수가 노출이 잘되는 걸 확인할 수 있다
상세페이지에서도 마찬가지로 노출이 잘된다
뭐 간단해서 따로 할 말은 없다...
위에 코드들을 응용 해서 "좋아요" 기능도 쉽게 만들 수 있을 거 같다
끝!
'Spring Boot' 카테고리의 다른 글
스프링부트 검색, 페이징처리 하기 Pageable - 2 - (0) | 2020.09.23 |
---|---|
스프링부트 검색, 페이징처리 하기 Pageable (0) | 2020.09.22 |
스프링부트에서 REST API 테스트코드 작성하기 (0) | 2020.09.14 |
게시판 게시글 정렬 하는법 (0) | 2020.09.11 |
[스프링부트 JPA] 연관관계 매핑 (0) | 2020.09.06 |