How to sort by multiple properties in Spring Data (JPA) derived queries?
JavaSpringJpaSpring DataSpring Data-JpaJava Problem Overview
I'm looking at the examples giving on this page (https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.repositories) about method naming, is it possible to create a complex chain method name such as
findByProgrammeAndDirectorAndProgDateBetweenOrderByProgDateStartTimeAsc
In the example they give, they are only doing an OrderBy on one value. In the example above ProgDate
and StartTime
would be two separate values.
Java Solutions
Solution 1 - Java
The trick is to simply delimit the properties you want to sort by using the direction keywords Asc
and Desc
. So what you probably want in your query method is something like:
…OrderByProgDateAscStartTimeAsc
Note, how we conclude the first property definition by Asc
and keep going with the next property.
Generally speaking, we recommend switching to @Query
based queries, once method names exceed a certain length or complexity. The main reason being that it's awkward for clients to call these very long methods. With @Query
you rather get the full power of the query language plus a reasonably sized method name that might be of higher level language to express the intent of the query.
Solution 2 - Java
Yes it's should be possible:
Try this:
findByProgrammeAndDirectorAndProgDateBetweenOrderByProgDateStartTimeAsc(String programme, String director, Date progStart, Date progEnd);
I have not tested the code, but according to things I've already done, it should work.
Solution 3 - Java
I am Sharing one other approach code snippet for implementing get operation where performing sort operation ordered by multiple column
List<Order> orders = new ArrayList<Order>();
Order StartTimeOrder = new Order(Sort.Direction.DESC, "StartTime");
orders.add(StartTimeOrder);
Order progDateOrder = new Order(Sort.Direction.ASC, "ProgDate");
orders.add(progDateOrder);
return repository.findAll(Sort.by(orders));