How Do You Specify Multi-Column Orderspecifier for Use in Springdata and Querydsl? Is This Possible

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

2 Answers

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:

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

2

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); 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest