How do you specify multi-column OrderSpecifier for use in SpringData and QueryDsl? Is this possible

StackOverflow https://stackoverflow.com/questions/20090098

  •  02-08-2022
  •  | 
  •  

Question

So I have the following query below:

public Iterable<Dealer> findAll(Dealer dealer) {
    QDealer qdealer = QDealer.dealer;

    BooleanExpression where = null;
    if(dealer.getId() != null && dealer.getId() != 0) {
        buildPredicate(qdealer.id.goe(dealer.getId()));
    }

    OrderSpecifier<String> sortOrder = QDealer.dealer.dealerCode.desc();
    Iterable<Dealer> results = dlrRpstry.findAll(where, sortOrder); 
    return results;
}

The query above works fine. However, I would like to sort the results by dealerType first, then by dealerCode somewhat like "order by dealerType asc, dealerCode desc". How do I instantiate the OrderSpecifier so that the results will be sorted by dealerType then by dealer code.

The DealerRepository dlrRpstry extends JpaRepository, QueryDslPredicateExecutor

I am using spring-data-jpa-1.1.0, spring-data-commons-dist-1.3.2 and querydsl-jpa-2.9.0.

If OrderSpecifier can not be configured to a multi-column sort order what would be the alternative solution that will satisfy my requirement of sorting the results "by dealerType asc, dealerCode desc".

Any help would be greatly appreciated. Thanks in advance.

Nick

Was it helpful?

Solution

I do not have JPA install setup, but I believe reading the QueryDslJpaRepository documentation, you can simply do this:

OrderSpecifier<String> sortOrder1 = QDealer.dealer.dealerType.asc();
OrderSpecifier<String> sortOrder2 = QDealer.dealer.dealerCode.desc();
Iterable<Dealer> results = dlrRpstry.findAll(where, sortOrder1, sortOrder2); 

Let us know if it works. Here is a link to a stackoverflow question/answer that explains the ... parameter syntax on the findAll() method:

https://stackoverflow.com/a/12994104/2879838

This means you can have as many OrderSpecifiers as you want as optional parameters to the function.

OTHER TIPS

If you don't want to create variable for each specifier, it can be done this way:

OrderSpecifier<?>[] sortOrder = new OrderSpecifier[] {
    QDealer.dealer.dealerType.asc(),
    QDealer.dealer.dealerCode.desc()
};
Iterable<Dealer> results = dlrRpstry.findAll(where, sortOrder); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top