Pagination and Sorting in Spring Boot

Pagination is the process of dividing data into separate pages.

Sorting is the process of ordering data in ascending or descending order.

The following code shows you how to use pagination and sorting in Spring Boot:

In Controller


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.data.web.SortDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(path = "/customers")
public class CustomerController {

    @Autowired
    private CustomerRepository customerRepository;
    
    @GetMapping(path = "/customers")
    public ResponseEntity<Page<CustomerDTO>> getCustomers(@PageableDefault(page = 0,
            size = 30) @SortDefault.SortDefaults({@SortDefault(sort = "createdDate",
                        direction = Sort.Direction.DESC)}) Pageable pageable) {
        Page<CustomerDTO> customers = customerRepository.findAll(pageable);
        return ResponseEntity.ok(customers);
    }

}

In Repository


import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface CustomerRepository extends CrudRepository<Customer, Integer> {

    public Page<Customer> findAll(Pageable pageable);
}