20

How do I pass a Pageable object to Spring JPA Repository with only Sorting information? I want something like this:

Pageable pageable = PageRequest.of(null, null, Sort());

I know it takes int as page and size but if we can somehow not use those values and give an unpaged result with only

Sort.by(Sort.Direction.ASC, "age")

We could use a high number like 1000 , 1000 for page and size but I do not want to hardcode these values.

I am also not looking to create a custom impl for Pageable.

Please let me know how to achieve this.

Thanks in advance.

Mohammed Idris
  • 768
  • 2
  • 9
  • 26

2 Answers2

7

According to the documentation for the current version of Spring Data JPA, you can pass a Sort directly to a query method, so you could have two versions of the same query method:

  • One receiving a Pageable, for use when you have a "full" Pageable.
  • Another one receiving a Sort, for use when you just want to perform sorting.
gpeche
  • 21,974
  • 5
  • 38
  • 51
  • 3
    This is a good option, having two methods in the repository class. However, what if I want to have only one method with `Pageable` as a parameter? Is it possible to achieve sorting using Pageable only? – Mohammed Idris Nov 08 '19 at 09:47
  • @MohammedIdris well `Pageable` is an interface so you can always make your own implementation. I guess you can use `org.springframework.data.domain.Unpaged` as a guide and provide a similar implementation that stores the `Sort` and returns it via `getSort`. Anyway, you should consider why you want to pass a `Pageable` if you do not want to do paging. – gpeche Nov 08 '19 at 09:57
  • I guess I could create an implementation, however, for passing `Pageable` but not using it, I already have a `Repository` method with `Pageable` which is being used by my `service class`. I thought of using the same method to get sorting without paging. If this is not possible I can create my own impl or I can add a method with `Sort` as a parameter. – Mohammed Idris Nov 12 '19 at 08:38
  • 2
    Really you can't. As soon as a **Pageable** with **isPaged=false** is provided the information in the Pageable is not used by **SimpleJpaRepository** class. The only way to go as an alternative if you want to use always a **Pageable** (so the **Sort** information is used) is to create a new one with **Integer.MAX_VALUE** as page size. – rubensa Jun 25 '20 at 05:33
  • @rubensa as far as i know max pages count in Pageable smaller as at Integer.MAX_VALUE – Zhenyria Jul 05 '21 at 14:31
-3

You could pass Pageable.unpaged() in the query and then sort the result (list.getContent().sort(Comparator.comparing(Item::getName))) if you are adamant about using the existing query.

Neha P
  • 13
  • 7