[Spring] Page, Slice

양정훈·2022년 6월 16일
0
  • 페이징 처리

Page

  • 총 데이터 갯수가 필요한 경우 사용, COUNT 쿼리 수행
// Controller

@GetMapping("/products/page")
public CommonResDTO<PageResDTO<Product>> getProductsByPage(Pageable pageable, @RequestParam String name) {
    Page<Product> products = productService.getProductsByPage(pageable, name);

    return new CommonResDTO<>(
        "SUCCESS",
        "done",
        new PageResDTO<>(products.getNumber(), products.getTotalElements(), products.getSize(), products.getContent())
    );
}
// Service

@Override
public Page<Product> getProductsByPage(Pageable pageable, String name) {
    return productRepository.findPageByName(name, PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), pageable.getSort()))
        .map(productEntity -> new Product(productEntity.getId(), productEntity.getName()));
}
// Repository

Page<ProductEntity> findPageByName(String name, Pageable pageable);

Slice

  • COUNT 쿼리 미수행
// Controller

@GetMapping("/products/slice")
public CommonResDTO<SliceResDTO<Product>> getProductsBySlice(Pageable pageable, @RequestParam String name) {
    Slice<Product> products = productService.getProductsBySlice(pageable, name);

    return new CommonResDTO<>(
        "SUCCESS",
        "done",
        new SliceResDTO<>(products.getNumber(), products.getSize(), products.hasNext(), products.getContent())
    );
}
// Service

@Override
public Slice<Product> getProductsBySlice(Pageable pageable, String name) {
    return productRepository.findSliceByName(name, PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), pageable.getSort()))
        .map(productEntity -> new Product(productEntity.getId(), productEntity.getName()));
}
// Repository

Slice<ProductEntity> findSliceByName(String name, Pageable pageable);

Request

/products?page=0&size=10&sort=id,DESC

0개의 댓글