简体   繁体   中英

Apply Order By in JPA Specifications

I'm writing code with the JPA Specifications:

Snippet1:

Specification.where(withTopics())
        .and(withCar())
        .and(withInsurance())
        // how to add order by

Where each condition method has structure like:

public static Specification<Page> withCar(String type) {
    return new Specification<Page>() {
      @Override
      public Predicate toPredicate(Root<Page> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        return // logic return cb
      }
    };
}

I want to add the the order by conditions.

I've written the order by expressions:

public static Specification<Page> orderByConditions(String input1, String input2) {
    return new Specification<Page>() {
      @Override
      public Predicate toPredicate(Root<Page> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        Expression<Object> cases = cb.selectCase()
                .when(cb.equal(cb.lower(root.get("carn_ame")), inputTopic.toLowerCase()), 1)
                .when(cb.like(cb.lower(root.get("insurance_name")), "%" + inputTitle.toLowerCase() + "%"), 2)
                .otherwise(3);
        Order order = cb.desc(cases);
        cb.createQuery().orderBy(order);
        // what to return
      }
    }
}

What should I return from my orderByConditions() , so I can apply it to my specifications in Snippet1 ?

But how should I add it to my specifications?

If you don't have a condition/predicate you can return a "no condition" 1 = 1

return cb.equal(cb.literal(1), 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM