Spring Data — Pagination and Sorting
Implement pagination with Spring Data JPA: Pageable, Sort, Slice, and custom page responses.
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.
JPA Entity Mapping with Relationships
Map entities with JPA annotations: OneToMany, ManyToOne, ManyToMany with fetch strategies and cascading.
Best for: Database schema design with JPA entities
Spring Data JPA — Custom Queries
Write custom JPA queries with @Query, derived methods, Specifications, and native SQL for complex lookups.
Best for: Complex database queries in Spring applications
Spring Data with Kotlin Repository Patterns
Use Spring Data JPA with Kotlin: entity mapping, custom queries, projections, and specifications.
Best for: Database access with Spring Data JPA in Kotlin
Java HttpClient — GET and POST Requests
Make HTTP requests with Java 11+ HttpClient: GET, POST JSON, async calls, and response handling.
Best for: Calling REST APIs from Java applications