본문 바로가기
Java/Spring Boot

[Spring Boot] 페이징(Paging)

by 깨준 2024. 10. 19.

1. 페이징(Paging)이란?

Paging은 사용자에게 데이터를 제공할 때, 전체 데이터 중의 일부를 보여주는 방식이다. 이 방식은 사용자에게 편히를 줄 뿐만 아니라, 전체 데이터를 로딩할 필요가 없어서 처리 속도가 빨라진다. Spring Data JPA에서 페이징을 쉽게 구현할 수 있는 기능을 제공한다.

2. 페이징의 기본 개념

페이징은 보통 페이지 번호(page)와 페이지 크기(size) 으로 작동한다.

  • page : 페이지 번호 (0부터 시작)
  • size : 한 페이지 당 데이터 개수

3. Spring Data JPA의 페이징 처리

Spring Data JPA에서는 Pageable과 Page<T> 인터페이스를 사용하여 페이징 처리를 할 수 있다.

  • Pageable 인터페이스
    Pageable pageable = PageRequest.of(page, size);
    
    보통 page와 size URL에서 쿼리 파라미터로 받아온다.
  • GET <http://localhost:8080/api/board/{boardId}/comment?page=0&size=5>
  • Pageable은 페이징 정보를 담고 있는 인터페이스이다. 주로 PageRequest.of() 메서드를 사용하여 Pageable 객체를 생성한다.
  • Page<T> 인터페이스
    • getContent(): 현재 페이지의 데이터 리스트
    • getTotalElements(): 전체 데이터 개수
    • getTotalPages(): 전체 페이지 수
    • getNumber(): 현재 페이지 번호
  • Page<T>는 페이징된 결과를 담는 인터페이스로, 전체 데이터 개수, 총 페이지 수, 현재 페이지의 데이터 등을 제공한다.

4. 페이징 예시(댓글 최신순)

Repository

public interface CommentRepository extends JpaRepository<Comment, Long> {
    Page<Comment> findByBoard_Id(Long boardId, Pageable pageable);
}

boardId에 해당하는 댓글을 Pageable 객체를 사용해 페이징

Service

@Transactional(readOnly = true)
public Page<CommentResponseDto> getComments(Long boardId, int page, int size) {
    boardRepository.findById(boardId)
            .orElseThrow(() -> new appException(ErrorCode.BOARD_NOT_FOUND));

    Pageable pageable = PageRequest.of(page, size);
    Page<Comment> allComments = commentRepository.findByBoard_Id(boardId, pageable);
    return CommentMapper.toCommentDtoPage(allComments);
}

boardId로 필터링된 댓글을 페이징 처리

 

Controller

@GetMapping("/api/board/{boardId}/comment/createdAt")
public ResponseEntity<Page<CommentResponseDto>> getCommentsCreateAts(
        @PathVariable Long boardId,
        @RequestParam int page,
        @RequestParam int size) {
    Page<CommentResponseDto> commentsCreateAt = commentService.getComments(boardId, page, size);
    return ResponseEntity.ok(commentsCreateAt);
}

http://localhost:8080/api/board/1/comment/createdAt?page=0&size=5 에서 요청
⇒ 첫번째 페이지에 5개 댓글 조회