Introduction

When working with databases in Java applications, queries often need to change based on user input or application requirements. For example, a search screen may allow users to filter records by name, age, status, or multiple conditions at the same time.

JPQL, HQL, and native SQL can handle these requirements, but dynamically building string-based queries can become difficult to maintain.

JPA provides the Criteria API, which allows developers to construct queries programmatically using Java objects and expressions. Hibernate supports the JPA Criteria API and can translate the resulting query into SQL for the underlying database.

In this article, we will learn how to use Criteria API with JPA/Hibernate to retrieve records, add conditions, combine multiple filters, and build dynamic queries.

What Is a Criteria Query?

A Criteria Query is a programmatic way to construct database queries using the JPA Criteria API.

Instead of writing a query as a string such as:

Java
SELECT u FROM User u WHERE u.age > 25

you construct the query using Java objects such as:

  • CriteriaBuilder

  • CriteriaQuery

  • Root

  • Predicate

This approach is particularly useful when query conditions are determined at runtime.

Why Use the Criteria API?

The Criteria API is useful when an application needs flexible query construction.

Type-Safe Query Construction

The Criteria API represents query components as Java objects rather than a single query string.

For even stronger type safety, you can use the JPA static metamodel instead of string-based property names.

Dynamic Queries

Conditions can be added only when they are required.

For example, a search page might allow users to provide:

  • Name

  • Minimum age

  • Maximum age

  • Account status

The application can construct the query based on whichever values were provided.

Object-Oriented Approach

Criteria queries work with entity classes rather than directly working with database tables.

Suitable for Complex Filtering

The API supports conditions, joins, ordering, grouping, aggregation, subqueries, and other query operations.

Setting Up the Example

For this example, assume a Java application using:

  • Java

  • JPA

  • Hibernate

  • An EntityManager

  • A relational database

The exact dependency configuration depends on whether you are using Spring Boot, Jakarta Persistence directly, or another Java framework.

Creating the User Entity

Let's create a simple User entity.

For modern Jakarta Persistence applications, the entity can be written as follows:

Java
import jakarta.persistence.Entity;
import jakarta.persistence.Id;

@Entity
public class User {

    @Id
    private Long id;

    private String name;

    private int age;

    public User() {
    }

    public User(Long id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

The User entity represents records in the database.

For older JPA versions, the imports may use javax.persistence instead of jakarta.persistence.

Fetching All Users

The first example retrieves all users.

Step 1: Get the CriteriaBuilder

The CriteriaBuilder is used to create expressions, predicates, and criteria queries.

Java
CriteriaBuilder cb = entityManager.getCriteriaBuilder();

Step 2: Create a CriteriaQuery

Create a query that will return User objects.

Java
CriteriaQuery<User> cq = cb.createQuery(User.class);

Step 3: Define the Query Root

The Root represents the entity from which the query starts.

Java
Root<User> root = cq.from(User.class);

Step 4: Select the Root

Select the users represented by the root.

Java
cq.select(root);

Step 5: Execute the Query

Java
List<User> users =
    entityManager.createQuery(cq).getResultList();

The complete example is:

Java
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;

import java.util.List;

CriteriaBuilder cb = entityManager.getCriteriaBuilder();

CriteriaQuery<User> cq = cb.createQuery(User.class);

Root<User> root = cq.from(User.class);

cq.select(root);

List<User> users =
    entityManager.createQuery(cq).getResultList();

Conceptually, the generated SQL is similar to:

SQL
SELECT *
FROM User;

The exact SQL generated by Hibernate depends on the entity mapping and database dialect.

Adding a WHERE Condition

Suppose we want users whose age is greater than 25.

With the Criteria API, use CriteriaBuilder to create the condition.

Java
cq.select(root)
  .where(cb.gt(root.get("age"), 25));

The important part is:

Java
cb.gt(root.get("age"), 25)

Here:

  • root.get("age") refers to the age property.

  • cb.gt() creates a greater-than condition.

  • 25 is the comparison value.

The query is conceptually equivalent to:

SQL
SELECT *
FROM User
WHERE age > 25;

Adding Multiple Conditions

Real applications commonly need more than one filter.

For example, suppose we want users who:

  • Are older than 25

  • Have names beginning with B

We can combine conditions using cb.and().

Java
Predicate ageCondition =
    cb.gt(root.get("age"), 25);

Predicate nameCondition =
    cb.like(root.get("name"), "B%");

cq.select(root)
  .where(cb.and(ageCondition, nameCondition));

The query is conceptually equivalent to:

SQL
SELECT *
FROM User
WHERE age > 25
AND name LIKE 'B%';

Using OR Conditions

The Criteria API also supports OR conditions.

For example:

Java
Predicate ageCondition =
    cb.gt(root.get("age"), 40);

Predicate nameCondition =
    cb.like(root.get("name"), "A%");

cq.select(root)
  .where(cb.or(ageCondition, nameCondition));

This represents:

SQL
SELECT *
FROM User
WHERE age > 40
OR name LIKE 'A%';

Adding Sorting

Criteria queries can also specify ordering.

Suppose we want users ordered by age in ascending order:

Java
cq.select(root)
  .orderBy(cb.asc(root.get("age")));

For descending order:

Java
cq.select(root)
  .orderBy(cb.desc(root.get("age")));

You can also sort by multiple properties:

Java
cq.orderBy(
    cb.asc(root.get("name")),
    cb.desc(root.get("age"))
);

Building a Dynamic Query

One of the strongest use cases for Criteria API is dynamic filtering.

Suppose a search screen allows the user to provide an optional name and minimum age.

We don't want to add a condition when the corresponding value was not provided.

Java
public List<User> searchUsers(
        EntityManager entityManager,
        String name,
        Integer minAge) {

    CriteriaBuilder cb =
        entityManager.getCriteriaBuilder();

    CriteriaQuery<User> cq =
        cb.createQuery(User.class);

    Root<User> root =
        cq.from(User.class);

    List<Predicate> predicates = new ArrayList<>();

    if (name != null && !name.isBlank()) {
        predicates.add(
            cb.like(
                cb.lower(root.get("name")),
                "%" + name.toLowerCase() + "%"
            )
        );
    }

    if (minAge != null) {
        predicates.add(
            cb.greaterThanOrEqualTo(
                root.get("age"),
                minAge
            )
        );
    }

    cq.select(root);

    if (!predicates.isEmpty()) {
        cq.where(
            cb.and(
                predicates.toArray(new Predicate[0])
            )
        );
    }

    cq.orderBy(cb.asc(root.get("name")));

    return entityManager
        .createQuery(cq)
        .getResultList();
}

This approach allows the same method to handle different combinations of search criteria.

For example:

Java
searchUsers(entityManager, "Bibek", 25);

can apply both filters.

While:

Java
searchUsers(entityManager, "Bibek", null);

can apply only the name filter.

And:

Java
searchUsers(entityManager, null, 25);

can apply only the age filter.

Understanding the Main Criteria API Components

Several classes are used repeatedly when working with Criteria API.

Component

Purpose

CriteriaBuilder

Creates queries, predicates, expressions, and ordering

CriteriaQuery<T>

Represents the query being constructed

Root<T>

Represents the entity used as the query source

Predicate

Represents a filtering condition

EntityManager

Creates and executes the query

A typical flow looks like this:

Code
EntityManager
     ↓
CriteriaBuilder
     ↓
CriteriaQuery
     ↓
Root
     ↓
Predicates / Ordering
     ↓
TypedQuery
     ↓
Database

Criteria API with Joins

Criteria API can also be used when entities have relationships.

For example, suppose a User has an Address.

Java
@Entity
public class Address {

    @Id
    private Long id;

    private String city;

    // Getters and setters
}

And the User entity contains:

Java
@ManyToOne
private Address address;

A query can join the entities:

Java
CriteriaQuery<User> cq =
    cb.createQuery(User.class);

Root<User> user =
    cq.from(User.class);

Join<User, Address> address =
    user.join("address");

cq.select(user)
  .where(
      cb.equal(address.get("city"), "Delhi")
  );

This allows the query to filter users based on properties of a related entity.

Criteria API vs JPQL

Both approaches have their place.

Feature

Criteria API

JPQL

Query format

Java API

String

Dynamic filters

Excellent

Requires careful construction

Readability

Can become verbose

Usually more concise

Refactoring

Better with static metamodel

String fields can be harder to refactor

Complex dynamic queries

Well suited

Can become difficult

Learning curve

Higher

Lower

For a simple fixed query, JPQL may be easier to read.

For example:

Java
List<User> users = entityManager
    .createQuery(
        "SELECT u FROM User u WHERE u.age > :age",
        User.class)
    .setParameter("age", 25)
    .getResultList();

The equivalent Criteria query is more verbose:

Java
CriteriaBuilder cb =
    entityManager.getCriteriaBuilder();

CriteriaQuery<User> cq =
    cb.createQuery(User.class);

Root<User> root =
    cq.from(User.class);

cq.select(root)
  .where(cb.gt(root.get("age"), 25));

List<User> users =
    entityManager.createQuery(cq)
                 .getResultList();

This illustrates an important point: Criteria API is not automatically better than JPQL. Its main advantage appears when query structure needs to change dynamically.

Improving Type Safety with the Static Metamodel

The examples above use:

Java
root.get("age")

and:

Java
root.get("name")

These property names are strings. If the entity property is renamed, the compiler cannot detect every string-based reference.

JPA also provides a static metamodel approach that can make Criteria queries more strongly typed.

Instead of:

Java
root.get("age")

you can use a generated metamodel attribute such as:

Java
root.get(User_.age)

The exact setup depends on the JPA/Hibernate version and annotation-processing configuration.

For larger applications with many Criteria queries, the static metamodel can make refactoring safer.

When Should You Use Criteria API?

Criteria API is particularly useful when:

  • Search filters are optional.

  • Queries contain many conditional predicates.

  • Joins are dynamically added.

  • Sorting is selected at runtime.

  • Queries are generated from structured search criteria.

  • You need programmatic control over query construction.

For simple, fixed queries, JPQL may provide better readability with less code.

Common Mistakes

Building Every Query with Criteria API

Criteria API is powerful, but it can be verbose.

If a query is fixed and simple, JPQL may be easier for another developer to understand.

Concatenating User Input into Queries

Avoid creating query strings by concatenating user input.

For example, do not build queries like:

Java
String query =
    "SELECT u FROM User u WHERE u.name = '"
    + userInput
    + "'";

Use parameters or Criteria API predicates instead.

Forgetting Optional Filters

When building dynamic queries, only add predicates when their corresponding values are available.

Otherwise, the query may unintentionally filter records.

Ignoring Database Performance

Criteria API helps construct queries, but it does not automatically make them efficient.

Complex joins, missing indexes, large result sets, and unnecessary database calls can still cause performance problems.

Always inspect the SQL generated by Hibernate when optimizing database access.

Best Practices

When using Criteria API in a production application:

  1. Keep query-building logic separate from business logic.

  2. Add predicates only when their filters are required.

  3. Prefer parameterized conditions over string concatenation.

  4. Use the static metamodel when stronger refactoring support is valuable.

  5. Avoid fetching more columns or records than necessary.

  6. Review generated SQL for complex queries.

  7. Use pagination for large result sets.

  8. Use JPQL when a query is fixed and Criteria API would add unnecessary complexity.

Conclusion

The JPA Criteria API provides a programmatic approach to constructing database queries in Java applications. It becomes particularly valuable when queries need to change dynamically based on search criteria, optional filters, joins, or sorting requirements.

The basic workflow is straightforward:

Code
CriteriaBuilder
      ↓
CriteriaQuery
      ↓
Root
      ↓
Predicate / Order / Join
      ↓
EntityManager
      ↓
Result

CriteriaBuilder, CriteriaQuery, Root, and Predicate form the foundation of most Criteria API queries.

Although Criteria API can be more verbose than JPQL, its programmatic structure makes it a strong option for applications with complex and dynamic query requirements. The key is to use it where dynamic query construction provides a real benefit rather than replacing every simple JPQL query with Criteria API.