Criteria API

Learn how to build queries programmatically using Hibernate's Criteria API. This approach is useful for constructing dynamic queries based on runtime conditions. We'll cover the basics of building criteria queries and executing them.


Building Basic Criteria Queries in Hibernate

This guide explains the fundamental concepts of building Criteria queries in Hibernate using Java. Criteria queries provide a type-safe way to construct database queries dynamically.

Fundamental Concepts

Building a Criteria query involves the following key objects:

  • CriteriaBuilder: This interface is the factory for CriteriaQuery and other query-related objects like predicates (conditions), expressions, and functions. You obtain a CriteriaBuilder from an EntityManager or Session.
  • CriteriaQuery: Represents an actual query. You define the query's selection criteria, ordering, and grouping using methods on this interface. Think of it as the blueprint for your SQL query.
  • Root: Represents the root entity of the query. It allows you to navigate the entity's attributes and relationships. It is also the starting point for constructing predicates and accessing data.

Creating CriteriaBuilder, CriteriaQuery, and Root

Here's how you create these essential objects:

 import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
import java.util.List;

public class CriteriaQueryExample {

    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit"); // Replace with your persistence unit name
        EntityManager em = emf.createEntityManager();

        try {
            // 1. Create a CriteriaBuilder
            CriteriaBuilder cb = em.getCriteriaBuilder();

            // 2. Create a CriteriaQuery
            CriteriaQuery<MyEntity> cq = cb.createQuery(MyEntity.class); // Specify the result type (MyEntity in this case)

            // 3. Create a Root
            Root<MyEntity> root = cq.from(MyEntity.class);  // Specify the entity to query from

            // The CriteriaQuery is now ready to be customized with selection criteria, ordering, etc.


            // Example: Selecting all entities of a specific type (MyEntity)
            cq.select(root); // Equivalent to "SELECT * FROM MyEntity"

            List<MyEntity> resultList = em.createQuery(cq).getResultList();

            for (MyEntity entity : resultList) {
                System.out.println(entity); // Assuming MyEntity has a toString() method or you can access its fields
            }

        } finally {
            em.close();
            emf.close();
        }
    }
} 

Important: Replace "my-persistence-unit" with the actual name of your persistence unit as defined in your persistence.xml file. Also, replace `MyEntity` with your actual entity class.

Selecting All Entities of a Specific Type

The example code demonstrates how to select all entities of a specific type. The cq.select(root) line instructs the query to select all attributes from the Root (which represents the entity type being queried).

 cq.select(root); // Equivalent to "SELECT * FROM MyEntity" in SQL 

This simple example serves as a foundation for building more complex criteria queries. You can add predicates (WHERE clauses), ordering (ORDER BY), and other features to refine your queries.

Remember to include the necessary JPA dependencies in your project (e.g., using Maven or Gradle). A typical dependency would look like this:

 <dependency>
                <groupId>org.hibernate.orm</groupId>
                <artifactId>hibernate-core</artifactId>
                <version>6.x.x</version> <!-- Replace with your Hibernate version -->
            </dependency> 

And a jakarta persistence api dependency, if you don't have it already:

 <dependency>
                <groupId>jakarta.persistence</groupId>
                <artifactId>jakarta.persistence-api</artifactId>
                <version>3.1.0</version> <!-- Or a later version -->
            </dependency>