Limit findAll possible with Spring?

前端 未结 3 662
名媛妹妹
名媛妹妹 2021-02-07 16:18

Is it possible with Springs auto implemented repositories to limit the result size of the findAll method?

I\'m trying to have something like the following declared in th

相关标签:
3条回答
  • 2021-02-07 16:40

    You need to explicitly specify the ordering, otherwise Spring Data JPA has no way of deciding what criteria it should use. For instance:

    List<XY> findAllTopTenByAge();
    

    See more details in the official documentation.

    0 讨论(0)
  • 2021-02-07 16:47

    Pass a Pageable as a parameter like following:

    Page<x> findAll(Pageable pageable);
    
    0 讨论(0)
  • 2021-02-07 16:53

    If you dont have a Pageable object that came from your controller and just need to get X amount of objects from DB, you can do the following:

    First, your Repository class has to extend JpaRepository<T, ID> so it wil be able to query using a Pageable object.

    Second, you can define a Pageable object this way:

    Pageable limit = PageRequest.of(0,10);
    return repository.findall(limit);
    

    In this case, the query would return the first 10 objects.

    You can find more info here (Scroll down to 4.1, Example 4) Note that the example actually extends PagingAndSortingRepository but JpaRepository contains all the methods from PagingAndSortingRepository and has additional functions aswell.

    Edit: Thanks to @Zunnii for pointing out that new PageRequest() is now deprecated. I edited the snippet above to reflect that.

    0 讨论(0)
提交回复
热议问题