BE/Spring Boot

[Spring Boot] 페이지네이션(Pagination) 적용

셰욘 2025. 2. 25. 20:45
728x90

페이지네이션(Pagenation)이란?

대량의 데이터를 일정한 크기(페이지)로 나누어 출력하는 방식이다.

-> 이 방식은 성능 최적화와 사용자 경험 개선을 위해 필수적으로 사용된다.


예를 들어, 데이터가 100개 있을 때 한 페이지당 10개씩 보여준다면 총 10페이지로 나누어 출력된다.


Spring Data JPA에서 페이징 처리

스프링 부트에서는 Spring Data JPA의 Page와 Pageable 인터페이스를 사용해서 간편하게 페이징을 구현할 수 있다.

 

 

DTO

페이징한 데이터를 담을 DTO 클래스를 생성한다.

Course를 페이징할 것이기 때문에 Course 응답 시 사용하는 CourseResponse를 List로 변수를 만든다.

 

  • page : 현재 페이지 번호
  • size : 한 페이지당 데이터 개수
  • totalElements : 전체 데이터 개수
  • totalPages : 전체 페이지 개수
  • hasNext : 다음 페이지 존재 여부
  • hasPrevious : 이전 페이지 존재 여부
  • courses : 현재 페이지의 데이터 목록
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public static class CoursePageResponse {
    private int page;
    private int size;
    private long totalElements;
    private int totalPages;
    private boolean hasNext;
    private boolean hasPrevious;

    private List<CourseResponse> courses;

    public static CoursePageResponse from(Page<Course> coursePage) {
        return CoursePageResponse.builder()
                .page(coursePage.getNumber())
                .size(coursePage.getSize())
                .totalElements(coursePage.getTotalElements())
                .totalPages(coursePage.getTotalPages())
                .hasNext(coursePage.hasNext())
                .hasPrevious(coursePage.hasPrevious())
                .courses(coursePage.stream().map(CourseDto.CourseResponse::from).collect(Collectors.toList()))
                .build();
    }
}

 

 


서비스

Page 인터페이스와 PageRequest 클래스를 사용해 데이터를 받아와 페이징 처리를 해준다.

page에는 조회할 페이지, size는 한 페이지에 넣을 개수를 뜻한다.

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
@Transactional(readOnly = true)
public CourseDto.CoursePageResponse list(int page, int size) {
    Page<Course> result = courseRepository.findAll(PageRequest.of(page, size));
    return CourseDto.CoursePageResponse.from(result);
}

 

 


컨트롤러

매개변수로 pagesize를 넘겨준다.

@GetMapping("/list")
public ResponseEntity<CourseDto.CoursePageResponse> list(int page, int size) {
    CourseDto.CoursePageResponse response = courseService.list(page, size);

    return ResponseEntity.ok(response);
}

 

728x90