Tapan
Tapan

Reputation: 187

Sort based on property values in spring boot

I am using the Sort feature provided in spring boot to sort my results. Consider an Entity "Employee" with properties like "id", "name" & "expertise".

"expertise" property can have values like "Java", "Python", "Admin", "Pascal" etc. I need to sort Employees based on expertise such that it is ordered as follows -

  1. Python
  2. Java
  3. Pascal
  4. Admin

Is there any way within the spring boot Sort feature to achieve such sorting?

Upvotes: 0

Views: 1306

Answers (2)

Tapan
Tapan

Reputation: 187

Found a working solution. For each expertise, I added a column of type integer with name as "order_number". Instead of using the expertise name, I started using the order_number column for sorting and it produced the desired results.

Upvotes: 1

Sridhar Patnaik
Sridhar Patnaik

Reputation: 1118

I am assuming that you are using paging and sorting repository. Without that you will not be able to sort. For paging and sorting repository, you have to extend you repository method to PagingAndSortingRepository<T, ID>

Now, when you invoke findall() method, you can pass your sort parameter as well. Example-

List<Employee> employees = repository.findAll(Sort.by(Sort.Direction.DESC, "expertise"));

Upvotes: 0

Related Questions