반응형
이번에는 게시글들을 정렬하는 서비스 로직을 추가해보았다. QueryDSL을 적용해보고자 하는 욕심은 있지만, 조금 더 시간을 가지고 JPA책을 완독하며 스프링 내부 구조를 파악한 이후에 제대로 적용해보고 싶다. 정적쿼리 정도는 쉽게 해볼 수 있지만 동적쿼리를 다루기 위해선 그래도 제대로 이해하고 활용하는게 더 맛있지 않을까 하는 생각이다.
게시글 정렬 서비스는 사용자 인증,인가 작업 없이 누구나 작업을 수행할 수 있게끔 만드는게 적절해보였다. Security configuration에 정렬uri를 예외사항으로 적어두고, 체인필터링과정에서도 해당 uri는 인증인가작업을 스킵하도록 적어두었다.
//controller method
@GetMapping("/sort/{type}")
public ResponseEntity<List<BoardResponseListDto>> sorting(@PathVariable("type") String type){
List<BoardResponseListDto> sortingRes = boardService.sorting(type);
return ResponseEntity.status(HttpStatus.OK).body(sortingRes);
}
// service method
public List<BoardResponseListDto> sorting(String type){
List<Board> boardList = new ArrayList<>();
if(Objects.equals(type, "commentCnt")){
boardList = boardRepository.findAllOrderByCommentCnt();
} else if (Objects.equals(type, "recommendCnt")) {
boardList = boardRepository.findAllOrderByRecommendCnt();
}
return boardList.stream().map(BoardResponseListDto::fromEntity).collect(Collectors.toList());
}
엔티티 객체 리스트를 dto 리스트로 변환해준 다음에 리턴시켜주는 방식을 계속 이용해왔다. db layer와 view layer를 분리시키기 위해서 꾸준히 dto를 만들어왔다.
// repository method
@Query("SELECT b FROM Board b ORDER BY b.commentCnt DESC, b.modifiedDate")
List<Board> findAllOrderByCommentCnt();
@Query("SELECT b FROM Board b ORDER BY b.recommendCnt DESC, b.modifiedDate")
List<Board> findAllOrderByRecommendCnt();
최다 순 내림차순으로, 만약 동일하다면 수정날짜 오름차순으로 리스트를 반환하게끔 jpql을 작성했다. 여긴 파라미터 바인딩은 필요없다고 판단하였고, 단순하게 코드를 작성했다.
간단하게 테스트코드도 작성했다.

여러번 테스트한다고 db에 게시글 정보를 몇 개 넣어두었었다.
@Test
@Transactional
public void sortTest(){
List<BoardResponseListDto> res = boardService.sorting("commentCnt");
for(BoardResponseListDto index: res){
logger.info(index.getContent());
}
}

최다댓글 순으로 정렬했을 때, 리턴되는 리스트의 content만 logger로 출력시켜보았다. 원하는 조건대로 잘 출력되었고, postman으로도 동일 과정을 진행했다.

게시글 정렬 서비스 구현을 마무리한다.
반응형
'Backend' 카테고리의 다른 글
| [Springboot] 금융 웹서비스 개발 프로젝트 - ChatGPT API 활용해서 대화해보기 (1) | 2024.01.27 |
|---|---|
| [SpringBoot] 게시판 만들기 (advanced type) (7) - 페이징 처리 (1) | 2024.01.18 |
| [SpringBoot] 게시판 만들기 (advanced type) (5) - 검색 서비스(제목, 글쓴이, 본문 내용을 키워드로 검색) (2) | 2023.12.26 |
| [SpringBoot] 게시판 만들기 (advanced type) (4) - 등급 별 총 회원 수 (0) | 2023.12.25 |
| [SpringBoot] 게시판 만들기 (advanced type) (3) - 회원탈퇴 (CascadeType.REMOVE) (2) | 2023.12.24 |