3

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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
reiley
  • 3,759
  • 12
  • 58
  • 114
  • 1
    Does this answer your question? [JpaSpecificationExecutor JOIN + ORDER BY in Specification](https://stackoverflow.com/questions/37203878/jpaspecificationexecutor-join-order-by-in-specification) – Simon Martinelli Apr 29 '20 at 09:29
  • @SimonMartinelli, I looked into it, but not able to figure out what `criteriaBuilder.equal`should I apply with `criteriaQuery.orderBy`. – reiley Apr 29 '20 at 09:32

1 Answers1

2

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

return cb.equal(cb.literal(1), 1);
Simon Martinelli
  • 34,053
  • 5
  • 48
  • 82