How to query data out of the box using Spring data JPA by both Sort and Pageable?

后端 未结 6 1635
别那么骄傲
别那么骄傲 2020-12-12 12:50

I am trying Spring data JPA in my project. I want to know if there is an out-of-the-box API to query data, by both Sort and Pageable. Of course, I

相关标签:
6条回答
  • 2020-12-12 13:24

    Pageable has an option to specify sort as well. From the java doc

    PageRequest(int page, int size, Sort.Direction direction, String... properties) 
    

    Creates a new PageRequest with sort parameters applied.

    0 讨论(0)
  • 2020-12-12 13:31

    In my case, to use Pageable and Sorting at the same time I used like below. In this case I took all elements using pagination and sorting by id by descending order:

    modelRepository.findAll(PageRequest.of(page, 10, Sort.by("id").descending()))
    

    Like above based on your requirements you can sort data with 2 columns as well.

    0 讨论(0)
  • 2020-12-12 13:34

    Spring Pageable has a Sort included. So if your request has the values it will return a sorted pageable.

    request: domain.com/endpoint?sort=[FIELDTOSORTBY]&[FIELDTOSORTBY].dir=[ASC|DESC]&page=0&size=20

    That should return a sorted pageable by field provided in the provided order.

    0 讨论(0)
  • 2020-12-12 13:35

    There are two ways to achieve this:

    final PageRequest page1 = new PageRequest(
      0, 20, Direction.ASC, "lastName", "salary"
    );
    
    final PageRequest page2 = new PageRequest(
      0, 20, new Sort(
        new Order(Direction.ASC, "lastName"), 
        new Order(Direction.DESC, "salary")
      )
    );
    
    dao.findAll(page1);
    

    As you can see the second form is more flexible as it allows to define different direction for every property (lastName ASC, salary DESC).

    0 讨论(0)
  • 2020-12-12 13:40

    in 2020, the accepted answer is kinda out of date since the PageRequest is deprecated, so you should use code like this :

    Pageable page = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), Sort.by("id").descending());
    return repository.findAll(page);
    
    0 讨论(0)
  • 2020-12-12 13:41
     public List<Model> getAllData(Pageable pageable){
           List<Model> models= new ArrayList<>();
           modelRepository.findAllByOrderByIdDesc(pageable).forEach(models::add);
           return models;
       }
    
    0 讨论(0)
提交回复
热议问题