JPA Criteria Query Selection and Results

The JPA Criteria API provides type-safe interfaces for defining query result expressions and ordering, mirroring the SELECT and ORDER BY clauses in JPQL or SQL. These interfaces allow you to specify exactly what data is returned and how it is sorted within the result set.

SELECT clause elements

The following interfaces represent the content of a SELECT clause:

Represents a single result item, such as an entity, an attribute, or a computed expression. Because Selection is a superinterface of Expression, most criteria expressions can be used directly in the SELECT clause.

Defines a selection composed of multiple items, commonly used for projections. It supports three types: arrays (CriteriaBuilder.array), application defined result classes  (CriteriaBuilder.construct), and tuples (CriteriaBuilder.tuple).

When compound selection results are returned as tuples:

Represents a single query result (result set row) and provides methods for obtaining the elements of the result as an array of objects or as individual values by index, alias string or TupleElement.

Represents a single selection in a compound selection and can be used to obtain the values of this selection in result tuples, rather than by index or string that are considered to be more error-prone (serves as the middle way between index access and using a dedicated  DTO result class).

For more information, see the SELECT in Criteria Queries section.

ORDER BY clause elements

Result ordering is represented by:

Specifies an ordering on a query expression, supporting both ascending and descending directions. You can create instances using CriteriaBuilder.ascjakarta.persistence.criteria.CriteriaBuilder.asc(Expression)Create an ordering by the ascending value of the expression. and CriteriaBuilder.descjakarta.persistence.criteria.CriteriaBuilder.desc(Expression)Create an ordering by the descending value of the expression..

Determines the precedence of null values during sorting, such as placing them first or last.

For more information, see the ORDER BY in Criteria Queries section.