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);
    }

}

CustomerRepository interface


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);
}

Customer Entity class


import java.time.LocalDateTime;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

@EntityListeners(AuditingEntityListener.class)
@Entity
@Table(name = "customer")
public class Customer {
	
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long id;
    private String firstName;
	private String lastName;
	private String nationality;
	private double balance;
	private String bankName;
	private String msisdnNumber;
	@CreatedDate
	private LocalDateTime createdDate;

	@LastModifiedDate
	private LocalDateTime modifiedDate;

	@CreatedBy
	private Long createdBy;

	@LastModifiedBy
	private Long modifiedBy;

	//getter and setter methods
}