JPA Criteria Queries

The Jakarta Persistence (JPA) Criteria API provides a type-safe, programmatic alternative to string-based JPQL for constructing dynamic queries, ensuring compile-time safety and facilitating easier refactoring.

It defines a structured hierarchy of interfaces for SELECT, UPDATE, and DELETE queries:

Criteria Queries Hierarchy in Jakarta Persistence (JPA) 3.2 

Instances of  CriteriaQuery, CriteriaUpdate, and CriteriaDelete are first built by static methods of CriteriaBuilder as mutable empty objects, and then defined using setter methods.

All query types (SELECT, UPDATE, and DELETE) inherit from the root interface:

This root interface provides shared functionality for restricting query scope using parameters and subqueries across all query types.

SELECT Queries

Build top-level retrieval queries using the main criteria query interface:

Use this interface to define SELECT, WHERE, GROUP BY, and ORDER BY clauses. To execute the query, pass the instance to EntityManager.createQueryjakarta.persistence.EntityManagerInterface used to interact with the persistence context. to obtain a TypedQueryjakarta.persistence.TypedQueryInterface used to control the execution of typed queries..

For nested queries within a main query, use:

Represents a query embedded within another query (for example, inside a WHERE clause). Unlike a top-level query, a subquery cannot be executed directly; it serves as an expression within the parent query (Note: Subqueries are currently not supported by ObjectDB).

Top-level queries and subqueries share functionality through their common parent:

This base interface defines the common structure of retrieval queries, including the ability to define roots and apply restrictions.

An interface that defines the result type of a selection query. It is extended by CriteriaQuery to support the definition of the SELECT clause.

The selection items (projection) are defined by the following functional interface:

UPDATE and DELETE Queries

CriteriaQuery is designed exclusively for data retrieval. Bulk data modifications are handled by the following interfaces:

Use this interface to define bulk update operations, set new attribute values, and restrict the scope with a WHERE clause.

Use this interface to define bulk delete operations based on specified conditions.