페이지네이션
기본적으로 많은 데이터를 조회하게 되면, 모든 데이터가 한 줄로 길게 출력되기에 가시성이 떨어진다. 제작 진행중인 일정 관리 어플리케이션은 전체 일정 조회라는 기능이 있어, 너무 많은 데이터를 출력하는 경우가 생긴다. 그렇기에 일정 페이지로 데이터를 나눠 출력하게 만드는 페이지네이션을 이번 일정 관리 프로젝트에 적용하였다.
@Getter
public class Paging {
private int page;
private int size;
private int startIndex;
private int endIndex;
public void handlePaging(int page, int size) {
this.page = page;
this.size = size;
this.startIndex = (page - 1) * size;
this.endIndex = startpage + size - 1;
}
}
먼저 Paging 클래스를 Entity 패키지에 만들었다. Paging 클래스는 기본적으로 현재 페이지, 페이지의 크기, 시작 인덱스, 마지막 인덱스를 변수로 갖는다. 생성자에서 현재 페이지와 페이지의 크기를 받아오면, 이를 계산해 다른 변수들을 초기화한다.
// Controller Layer
@GetMapping("/pages")
public ResponseEntity<List<ScheduleDataResponseDto>> pagingList(
@RequestParam Integer page,
@RequestParam Integer size
) {
return new ResponseEntity<>(scheduleService.pagingList(page, size), HttpStatus.OK);
}
// Service Layer
public List<ScheduleDataResponseDto> pagingList(int page, int size) {
// 페이지 및 사이즈 값이 잘못되면 오류 메시지 출력
if (page < 1 || size < 1) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "잘못된 페이지 설정입니다.");
}
return scheduleRepository.pagingList(page, size);
}
// Repository Layer
public List<ScheduleDataResponseDto> pagingList(int page, int size) {
Paging paging = new Paging();
paging.handlePaging(page, size);
return jdbcTemplate.query("select * from schedule limit ?, ?", ScheduleRowMapper(), paging.getStartIndex(), paging.getSize());
}
1. Controller Layer에서 파라미터로 현재 페이지와 페이지 크기를 받는다.
2. Service Layer에서 입력된 파라미터가 올바른 값인지 확인한다.
3. Repository Layer에서 페이징 작업을 실행한다.
페이징 작업은 간단하게 startIndex를 Get으로 받고 쿼리문에 입력하는 것이 전부다. limit를 이용하면 schedule 테이블에 있는 Row들을 원하는 수 만큼 가져올 수 있다. 또한 요청받은 페이지가 기존 데이터의 범위를 초과할 경우 빈 배열을 출력한다. endIndex는 추후 기능을 추가할 때 이용할 더미 데이터로 남겼다.