Pageable 인터페이스는 Spring Data JPA에서 페이징과 정렬 정보를 전달하는 표준 방식을 제공합니다. 이를 통해 클라이언트 요청에 기반한 동적 페이징과 정렬 처리가 가능하며, 리포지토리 메소드에 Pageable 객체를 파라미터로 넘겨주면, Spring Data JPA가 이 정보를 바탕으로 SQL 쿼리를 자동으로 생성해줍니다.
Pageable 객체에 담긴 페이징과 정렬 조건에 맞게 결과를 Page<Entity> 형태로 반환합니다. 여기서 Page< Entity >는 검색된 게시글의 페이지 정보를 포함하고 있어, 개발자는 이를 활용하여 프론트엔드에 필요한 페이징 정보(예: 현재 페이지 번호, 총 페이지 수, 페이지 당 게시글 수 등)를 쉽게 제공할 수 있습니다.
1. 리포지토리 인터페이스 정의
public interface ProductRepository extends JpaRepository<Product, Long> {
Page<Product> findByNameContaining(String name, Pageable pageable);
}
Name뿐만아니라 다른것도 포함시켜서 검색하고싶으면 or을 붙이면 됩니다.
ex)
Page<Post> findByTitleContainingOrContentContaining(String title, String content, Pageable pageable);
2. 서비스 계층 구현
@Service
public class ProductService {
private final ProductRepository productRepository;
public ProductService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
public Page<Product> searchProducts(String name, Pageable pageable) {
return productRepository.findByNameContaining(name, pageable);
}
}
3. 컨트롤러 구현
@RestController
public class ProductController {
private final ProductService productService;
public ProductController(ProductService productService) {
this.productService = productService;
}
@GetMapping("/products/search")
public ResponseEntity<Page<Product>> searchProducts(
@RequestParam String name,
@PageableDefault(size = 10, sort = "id", direction = Sort.Direction.DESC) Pageable pageable) {
Page<Product> page = productService.searchProducts(name, pageable);
return ResponseEntity.ok(page);
}
}
반응형
'Java > Spring' 카테고리의 다른 글
[Spring]@ManyToOne, @OneToMany 엔티티간 다대일, 일대다 관계 설정 (0) | 2024.04.29 |
---|---|
[Java] DTO 쉽게 만드는 법 (record) (0) | 2024.04.27 |
[Spring]@PageableDefault (페이징 처리) (0) | 2024.04.08 |
[Spring] @DeleteMapping 사용방법 (0) | 2024.04.02 |
[Spring]Model 객체와 @ModelAttribute (0) | 2024.04.02 |