Home > Spring > Spring Boot > Spring Boot – Pagination, Sorting operations

Spring Boot – Pagination, Sorting operations

While developing any spring boot API, We create many rest endpoints for the CRUD operation on data, which deals with large volume of data. Because of the large volume, fetching of records from database takes more time. To overcome this types of cases we have some options in hand.

  1. Set limit for every request.
  2. Use pagination in fetching the records from database.
  3. Apply criteria/filters in database queries

By applying the above strategies we can fetch relevant data in small chunks in multiple requests. Like fetching 50 records in every request with proper filter/criteria and sorted by some meaningful fields.

Now in the development part, follow the below mentioned steps-

  1. Create a spring boot project.
  2. Create different packages like (entity, model, repo, service, controller, config, util etc.)
  3. Create a few CRUD API endpoints (Like create a employee, get all employees)

PagingAndSortingRepository

In our spring boot project, for implementing paging and sorting, we need to extend PagingAndSortingRepository in our EmployeeRepository interface.

@Repository
public interface EmployeeRepository extends PagingAndSortingRepository<Employee, Integer> {

}
PagingAndSortingRepository is an extension of CrudRepository. PagingAndSortingRepository has two methods-
Page<T> findAll(Pageable pageable);
Iterable<T> findAll(Sort sort);

Service Layer

@Override
public List<User> getEmployeesByPagination(int pageNo, int pageSize) {

    //create PageRequest object
    PageRequest pageRequest = PageRequest.of(pageNo, pageSize);

    //pass pageRequest to repository
    Page<User> pagingUser = employeeRepository.findAll(pageRequest);

    //pagingUser.hasContent(); -- to check pages are there or not
    return pagingUser.getContent();
}

Controller Layer

@GetMapping
public List<Employee> getEmployeesByPagination(@RequestParam(defaultValue = "0") Integer pageNo,
                                    @RequestParam(defaultValue = "50") Integer pageSize){

    return employeeService.getEmployeesByPagination(pageNo,pageSize);

}

Page Number starts from zero and Page Size is the number of records per page. Sometimes the user doesn’t want to pass these values from the URL, in that case it will take the default value as mentioned in the signature.

Sorting

Now we will implement sorting in the above mentioned application.

PageRequest pageRequest = PageRequest.of(pageNo, pageSize, Sort.by("name").ascending());

For single parameter sorting we can use the above technique, but if we have to pass multiple params for sorting than we will use the below mentioned way-

Sort employeeIdSort = Sort.by("id");
Sort nameSort = Sort.by("name");

Sort multiSort = nameSort.and(employeeIdSort);

List<EmployeeEntity> result = repository.findAll(multiSort);

So this is all about paging and sorting in Spring Boot projects.