Pagination, Sorting and Searching are essential data retrieval techniques used in web applications and REST APIs to handle large datasets efficiently. Instead of loading thousands of records into memory at once—which degrades performance, consumes excessive network bandwidth, and slows down client applications—these techniques allow clients to retrieve data incrementally, in a specific order, and filtered by targeted criteria.
1. Pagination
Pagination is the process of dividing a large result set into smaller, manageable chunks called pages.
-
Core Interfaces: In Spring Data, pagination is built around the
Pageableinterface and its standard implementation,PageRequest(e.g.,PageRequest.of(pageNumber, pageSize)). -
Response Types:
-
Page<T>: Returns the data elements along with pagination metadata, such astotalElements,totalPages,isLast, andhasNext(requires an extra SQLCOUNTquery behind the scenes). -
Slice<T>: Returns only whether a next slice is available without executing a count query, making it more efficient for infinite scroll interfaces.
-
-
SQL Translation: Translated under the hood into database-level offset and limit clauses (e.g.,
LIMIT ? OFFSET ?) so only the requested page of rows is transferred from the database.
2. Sorting
Sorting controls the order in which records are returned from the database based on one or more entity attributes.
-
SortClass: Spring Data uses theSortobject to define sorting criteria (e.g.,Sort.by("createdAt").descending()or chaining multiple fields likeSort.by("department").ascending().and(Sort.by("salary").descending())). -
Repository Integration: Can be passed directly into repository methods (e.g.,
repository.findAll(sort)) or embedded within aPageableinstance. -
SQL Translation: Appends standard SQL
ORDER BYclauses to the generated query, leveraging database indexes for fast ordering.
3. Search
Search refers to filtering and querying datasets to locate records that match specific conditions or patterns.
-
Derived Query Filters: Expressed through repository method names using keywords like
Containing,IgnoreCase,Between, orStartingWith(e.g.,findByNameContainingIgnoreCase(String keyword)). -
Dynamic Search (JPA Specifications / QueryDSL): Uses the JPA Criteria API (
Specification<T>) to construct dynamic SQL queries at runtime, allowing users to apply optional and variable search filters without writing multiple permutations of queries. -
Full-Text & Index Search: Employs database-level text indexes, pattern matching (
LIKE %keyword%), or external engines (like Elasticsearch) for advanced text search capabilities.
4. Combined Search, Sorting and Pagination
In production-grade applications, searching, sorting, and pagination are almost always used together to build responsive, filterable data tables and search endpoints.
-
Controller-Level Input: REST endpoints receive query parameters such as
?page=0&size=10&sortBy=price&direction=desc&query=laptopvia@RequestParamor an injectedPageableobject. -
Single Database Execution: Spring combines the filter criteria (Search),
ORDER BYclause (Sorting), andLIMIT/OFFSET(Pagination) into a single optimized SQL statement. -
Unified API Response: Returns a structured JSON payload containing the requested page of matching items alongside pagination metadata (current page, total pages, sort state), providing everything the client-side UI needs to render navigation controls and data tables.
