티스토리 뷰

카테고리 없음

Pageable

eyoadgkn 2024. 6. 6. 22:30
Pageable
Pageable은 Spring Data JPA에서 사용되는 인터페이스로, 페이징 처리를 위한 정보를 제공합니다.
이를 통해 데이터베이스에서 전체 데이터를 가져오는 것이 아니라, "페이지 단위"로 데이터를 가져올 수 있습니다.

Pageable 인터페이스
pageNumber: 현재 페이지 번호 (0부터 시작)
pageSize: 한 페이지에 표시할 데이터의 수
sort: 정렬 조건
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.entity.Product;
import com.example.demo.repository.ProductRepository;

@RestController
public class ProductController {

    private final ProductRepository productRepository;

    public ProductController(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    @GetMapping("/products")
    public Page<Product> getProducts(@RequestParam(defaultValue = "0") int page,
                                    @RequestParam(defaultValue = "10") int size,
                                    @RequestParam(defaultValue = "id") String sort) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(sort));
        return productRepository.findAll(pageable);
    }
}

 

/products 엔드포인트에 GET 요청이 오면, Pageable 객체를 생성하여 ProductRepository의 findAll 메서드에 전달합니다.
이를 통해 페이지 번호, 페이지 크기, 정렬 조건에 따른 Product 엔티티 데이터를 반환합니다.
클라이언트에서는 page, size, sort 파라미터를 전달하여 원하는 페이지의 데이터를 요청할 수 있습니다.
예를 들어, ?page=1&size=20&sort=name과 같이 요청하면 2번째 페이지의 20개 데이터를 이름 순으로 정렬하여 반환합니다.
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함