Nane Petrosyan
Nane Petrosyan

Reputation: 613

Spring data sort by nested property

I am using pagination in spring boot. When getting a page from DB, i want to sort data by a nested property. Here is the code where I create a Page request .

Pageable pageOfElements = PageRequest.of(pageNumber, pageSize, Sort.by("customDateObject").descending());

my custom object implements comparable, but sorting does not work, how can I fix this? Thank you in advance.

Upvotes: 1

Views: 4056

Answers (1)

Sebastian Grigor
Sebastian Grigor

Reputation: 174

You can nest properties inside your sort by parameter:

Pageable pageOfElements = PageRequest.of(pageNumber, pageSize, Sort.by("customDateObject.customProperty").descending());

So for example, if you are sorting Cars by the id of their owner, you would do the following:

Sort.by("owner.id")

Upvotes: 5

Related Questions