스프링 미니 프로젝트 - JPA Pageable

Zyoon·2025년 5월 24일

미니프로젝트

목록 보기
13/36
post-thumbnail

📘JPA Pageable 사용하여 게시글 Pasing 하여 가져오기


0. JPA Pageable

  • 페이징과 정렬을 간편하게 처리하도록 도와주는 인터페이스
  • 게시글을 조회할 때 정렬 기준(최신순, 좋아요순)과 정렬방식(오름차순, 내림차순)을 쉽게 구현할 수 있다.

1. 주요 메서드 및 생성방법

  • Pageable 생성
Pageable pageable = PageRequest.of(page, size, Sort.by("id").descending()); 
- page : 요청하는 페이지 번호. 첫 페이지는 0.
- size : 한 페이지에 포함할 항목 수.
- Sort.by("id")
  • 주요 메서드
int getPageNumber()	//현재 페이지 번호 (0부터 시작)

int getPageSize()	//한 페이지에 몇 개의 요소를 가져올지

long getOffset()	//현재 페이지의 시작 offset (LIMIT, OFFSET에 사용)

Sort getSort()	//정렬 정보 가져오기

Pageable next()	//다음 페이지 요청용 Pageable 생성

Pageable previousOrFirst()	//이전 페이지 또는 첫 페이지 반환

Pageable first()	//첫 번째 페이지로 이동한 Pageable 반환

boolean hasPrevious()	//이전 페이지가 존재하는지 여부

2. 예시 코드

Controller

  • pagesize 는 파라미터를 넘기지 않는 경우에도 사용할 수 있도록 하기 위해 @RequestParam 타입으로 넘겨준다.
  • pagedefaultValue 는실제 페이지 번호와 동일하게 적용하기 위해 1 로 설정을 해 놓았고, service 로 파라미터를 넘길때는 page-1 로 넘겨서 Pageable 의 인덱스 번호와 맞춰줬다.
  • service 로 부터 반환받는 타입은 Page<Dto> 로 받는다.
  • Page 타입을 getContent() 메서드로 List 타입으로 반환한다.
@GetMapping
public ResponseEntity<List<BoardResponseDto>> getPagedBoards(
        @RequestParam(defaultValue = "1") int page,
        @RequestParam(defaultValue = "10") int size){
    
    Page<BoardResponseDto> pagedBoardList = boardService.getPagedBoards(page-1, size);
    
    return new ResponseEntity<>(pagedBoardList.getContent(), HttpStatus.OK);
}

Service

  • @Transactional(readOnly = true) : 읽기 전용 트랜잭션. 성능 최적화를 위해 사용한다.
  • Pageable : 전달받은 page(페이지 번호), size(항목 수) 로 생성해준다.
  • findAllByOrderByCreatedAtDesc : createdAt 기준으로 내림차순 정렬된 게시글을 페이징하여 조회한다.
  • map() : 각 객체를 Dto 로 변환해준다.
@Transactional(readOnly = true)
public Page<BoardResponseDto> getPagedBoards(int page, int size) {

    Pageable pageable = PageRequest.of(page, size);

    Page<Board> pagedBoardList = boardRepository.findAllByOrderByCreatedAtDesc(pageable);

    return pagedBoardList.map(BoardResponseDto::new);
}

Repository

  • 쿼리 메서드에 pageable 객체를 넘겨서 Page 타입을 반환받는다.
public interface BoardRepository extends JpaRepository<Board, Long> {

    Page<Board> findAllByOrderByCreatedAtDesc(Pageable pageable);
}

//실행되는 SQL : SELECT * FROM board ORDER BY created_at DESC LIMIT ? OFFSET ?;

Client

  • 요청시 page, size 가 없다면 defaultValue 로 요청된다.
GET /boards // defaultValue

GET /boards?page=2&size=5 // 페이지번호와 게시글 수 요청
profile
기어 올라가는 백엔드 개발

0개의 댓글