Search code examples
javahibernatespring-data-jpahibernate-criteria

Criteria API. Predicate with OrderBy expression


I have a repo with own Specification implementation with toPredicate method as main query construction and I try to add order by expression:

public Predicate toPredicate(@NotNull Root<Strategy> root,
                             @NotNull CriteriaQuery<?> query,
                             @NotNull CriteriaBuilder builder) {
     Predicate predicate = builder.conjunction();
     List<Expression<Boolean>> exps = predicate.getExpressions();

     ... adding different expressions to exps.add(...)

     // I get an id for descending sort due to Postgres just increment it.
     Order orderBy = builder.desc(root.get("id"));
     Expression<?> expression = orderBy.getExpression();

     // Problem here.
     exps.add(expression);
     return predicate;
}

Expression from orderBy.getExpression() is <?> generic but original expressions list expect <Boolean> type. How to connect them?


Solution

  • Specification is only intended for encoding where-clauses. If you want to order your result use a Sort instance as an additional parameter.