Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create unpaged but sorted Pageable.of(unpaged, unpaged, Sort ) to spring data jpa repository?

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.

like image 829
Mohammed Idris Avatar asked Nov 08 '19 07:11

Mohammed Idris


People also ask

How do I set Pageable sort?

Use PageableDefault annotation on the Pageable parameter to set default values for page number and page size. Use SortDefault to set default sort along with direction; and then you can also set multiple default sorts.

How do you sort data in spring boot?

4.1. One option is to use Spring Data's method derivation, whereby the query is generated from the method name and signature. All we need to do here to sort our data is include the keyword OrderBy in our method name, along with the property name(s) and direction (Asc or Desc) by which we want to sort.

What is pagination and sorting in spring boot?

Paging and sorting is mostly required when we are displaying domain data in tabular format in UI. Pagination consist of two fields – page size and page number. Sorting is done on a single of multiple fields in the table.

How does JPA findById work?

Its findById method retrieves an entity by its id. The return value is Optional<T> . Optional<T> is a container object which may or may not contain a non-null value. If a value is present, isPresent returns true and get returns the value.


1 Answers

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.
like image 170
gpeche Avatar answered Oct 21 '22 02:10

gpeche