Pavel
Pavel

Reputation: 2101

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?

Upvotes: 0

Views: 2266

Answers (2)

Pavel
Pavel

Reputation: 2101

Sorting with pagination means sorting should be field of Pageable like this:

Pageable pagination = PageRequest.of(pageNumber, pageSize, Sort.by("id").descending());

Upvotes: 0

Jens Schauder
Jens Schauder

Reputation: 81862

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

Upvotes: 2

Related Questions