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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With