Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort records using Pageable with given order

I am working on a spring boot project and have the get API to display the records from the database with certain filters along with pagination to achieve that I am using the JPA with JPA Specifications. API is working fine with given filter options and paginations params. Now I want to sort them based on the field with a decs|asc order dynamically.

API

@GetMapping("/opportunities")
  public ResponseEntity<List<Opportunities>> findAll(Pageable pageable,
      @RequestParam(required = false) String ..,
      @RequestParam(required = false) String ..,
      @RequestParam(required = false) String ..,
      @RequestParam(required = false) Boolean ..,
      @RequestParam(required = false, defaultValue = "true") boolean ..) {
    opportunityService.findAll(..., pageable);
  }

Method

  @Override
  public Page<Opportunity> findAll(String .., String .., String ..,
      Boolean .., boolean .., Pageable pageable) {

    OpportunityFilters opportunityFilters = new OpportunityFilters();
    ... // set filters
    OpportunitySpecification opportunitySpecification =
        new OpportunitySpecification(opportunityFilters);
    Page<Opportunity> page = opportunityRepository.findAll(opportunitySpecification,
        pageable);
    ...
}  

OpportunityRepository.java

@Repository
public interface OpportunityRepository extends JpaRepository<Opportunity, String>,
    JpaSpecificationExecutor<Opportunity> {
}

When I hit the API with the sort param and set the field name it sort the records properly but I want to set the sort order dynamically in the request. How can I set the sort order here?

http://localhost:8080/api/opportunities?page=0&size=10&sort=name

like image 667
anonymous Avatar asked Sep 17 '25 21:09

anonymous


1 Answers

You can do it adding the sort direction (,asc, or ,desc) in the sort parameter of the API request. For example, if you want to sort by the name field in descending order, you can make the following request:

http://localhost:8080/api/opportunities?page=0&size=10&sort=name,desc

Spring Boot will automatically handle this.

like image 151
rMonteiro Avatar answered Sep 19 '25 12:09

rMonteiro