controller
@GetMapping("/api/townbooks/page")
public Page<TownBook> getAllBooks(
@RequestParam("page") int page,
@RequestParam("size") int size,
@RequestParam("sortBy") String sortBy,
@RequestParam("isAsc") boolean isAsc
) {
page = page - 1;
return townBookService.getAllBooks(page , size, sortBy, isAsc);
}
보여주고 싶은 페이지 번호와 보여지고 싶은 갯수, 어떤 것으로 정렬을 할 것인지, 오늘차순 또는 내림차순 중 어떤 것으로 정렬을 하고 싶은지 받아와서 보내주 값으로 서비스에서 처리를 합니다.
Service
public Page<TownBook> getAllBooks(int page, int size, String sortBy, boolean isAsc) {
Sort.Direction direction = isAsc ? Sort.Direction.ASC : Sort.Direction.DESC;
Sort sort = Sort.by(direction, sortBy);
Pageable pageable = PageRequest.of(page, size, sort);
return townBookRepository.findAllByOrderByCreatedAtDesc(pageable);
}
오름차순과 내림차순중 어떤 것으로 정렬을 할 것인지 TRUE or FALSE로 선택한다.
Repository
Page<TownBook> findAllByOrderByCreatedAtDesc(Pageable pageable);
Repository에서는 어떤 것으로 정렬을 할 것인지 적는다.
생성 날짜 순으로 데이터를 보내주려고 CreatedAt를 선택해서 적었다.
'Spring' 카테고리의 다른 글
@Autowired (0) | 2021.05.17 |
---|---|
hibernate란? (0) | 2021.05.09 |
Spring VS Node.js (0) | 2021.04.25 |