reiley
reiley

Reputation: 3761

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?

Upvotes: 3

Views: 1766

Answers (1)

Simon Martinelli
Simon Martinelli

Reputation: 36133

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

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

Upvotes: 2

Related Questions