javabeginner

Spring Data — Pagination and Sorting

Implement pagination with Spring Data JPA: Pageable, Sort, Slice, and custom page responses.

java
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/products")
public class ProductController {
    private final ProductRepository repo;

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

    // GET /api/products?page=0&size=20&sort=price,desc
    @GetMapping
    public PageResponse<ProductDTO> findAll(
        @RequestParam(defaultValue = "0") int page,
        @RequestParam(defaultValue = "20") int size,
        @RequestParam(defaultValue = "createdAt,desc") String sort
    ) {
        String[] parts = sort.split(",");
        Sort sortBy = Sort.by(
            parts.length > 1 && parts[1].equalsIgnoreCase("asc")
                ? Sort.Direction.ASC : Sort.Direction.DESC,
            parts[0]
        );
        Pageable pageable = PageRequest.of(page, Math.min(size, 100), sortBy);
        Page<Product> result = repo.findAll(pageable);

        return new PageResponse<>(
            result.getContent().stream().map(this::toDTO).toList(),
            result.getNumber(),
            result.getSize(),
            result.getTotalElements(),
            result.getTotalPages(),
            result.hasNext()
        );
    }

    // Search with pagination
    @GetMapping("/search")
    public Page<ProductDTO> search(
        @RequestParam String q,
        Pageable pageable // Spring auto-binds page, size, sort
    ) {
        return repo.findByNameContainingIgnoreCase(q, pageable)
            .map(this::toDTO);
    }

    private ProductDTO toDTO(Product p) {
        return new ProductDTO(p.getId(), p.getName(), p.getPrice());
    }
}

record PageResponse<T>(
    List<T> content,
    int page,
    int size,
    long totalElements,
    int totalPages,
    boolean hasNext
) {}

record ProductDTO(Long id, String name, Double price) {}

Sponsored

Supabase

Use Cases

  • Paginated API responses for large datasets
  • Server-side sorting and filtering
  • Search endpoints with pagination support

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.