escape-room

[Spring] Pageable 설정하기 (글로벌 설정, 개별 설정)

기매_ 2023. 5. 18. 22:19

글로벌 설정

application.yml로 설정하기

spring:
  data:
    web:
      pageable:
        default-page-size: 12
        max-page-size: 200
        one-indexed-parameters: true

 

default-page-size : 기본 페이지 사이즈

max-page-size : 요청할 수 있는 최대 페이지 사이즈

one-indexed-parameters : true로 했을 경우 페이지 사이즈가 1번부터 시작 (원래는 0번부터 시작한다)

 

이 외에도 Spring 에서는 다양한 설정들을 제공해주고 있다.

아래 스프링 공식문서를 참고해서 사용해볼 것 !

https://docs.spring.io/spring-boot/docs/2.2.2.RELEASE/reference/html/appendix-application-properties.html#common-application-properties

 

Common Application properties

Various properties can be specified inside your application.properties file, inside your application.yml file, or as command line switches. This appendix provides a list of common Spring Boot properties and references to the underlying classes that consume

docs.spring.io


개별 설정

1. @PageableDefault 사용

@GetMapping("/cafe/all")
public Page<CafeDTO> cafeAllList(@PageableDefault(size = 12, sort = "name") Pageable pageable) {
    return cafeService.cafeAllList(pageable);
}

 

https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/web/PageableDefault.html

 

PageableDefault (Spring Data Core 3.1.0 API)

Since: 1.6 Author: Oliver Gierke, Mark Paluch Optional Element Summary Optional Elements The direction to sort by. int The default page number the injected Pageable should use if no corresponding parameter defined in request (default is 0). int The default

docs.spring.io


2. PageRequest 사용

PageRequest pageRequest = PageRequest.of(0, 3, Sort.by(Sort.Direction.DESC, "username"));

Slice<Member> page = memberRepository.findSliceByAge(age, pageRequest);

필요한 대로 PageRequest 객체를 만들어 Pageable 파라미터로 넣어주면 된다 !

 

PageRequest.of(0, 3, Sort.by(Sort.Direction.DESC, "username")) 에서

파라미터는 순서대로 page, size, sort 이다.

 

참고

https://velog.io/@conatuseus/JPA-Paging-%ED%8E%98%EC%9D%B4%EC%A7%80-%EB%82%98%EB%88%84%EA%B8%B0-o7jze1wqhj

 

JPA Paging (페이지 나누기)

현재 2개의 프로젝트 진행하고 있다. > 두 프로젝트 모두 글 또는 영상을 페이징해서 프론트에 뿌려주는 API가 필요했다. > 그래서 이번에 PageRequest를 사용해 페이징 하는 것을 공부했고 공유하고

velog.io