Sobes.tech
Middle

What is Criteria API and how to use it in Java for database operations?

sobes.tech AI

Answer from AI

Criteria API is an object-oriented way to construct database queries. It provides a set of classes and interfaces for programmatically creating queries, making them type-safe and easier to build dynamically. It is an alternative to HQL (Hibernate Query Language) and native SQL queries in JPA (Java Persistence API).

Advantages:

  • Type safety: Errors are detected at compile time rather than at runtime.
  • Object-oriented: Queries are built using Java objects.
  • Dynamic construction: Convenient for creating queries with variable conditions.
  • Readability: A query written using the Criteria API is more understandable than a formatted SQL string.

Main components:

  • CriteriaBuilder: Factory for creating CriteriaQuery, Path, expressions, and predicates.
  • CriteriaQuery: Represents the executable query.
  • Root: Represents the root entity in the query.
  • Path: Represents navigation through entity properties.
  • Predicate: Represents a condition in the query (e.g., equality, greater than, less than).
  • Expression: Represents an operation or value in the query.

Example of usage for selecting all entities:

// obtaining CriteriaBuilder
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
// creating CriteriaQuery for entity type MyEntity
CriteriaQuery<MyEntity> query = cb.createQuery(MyEntity.class);
// defining the root entity
Root<MyEntity> root = query.from(MyEntity.class);
// executing the query
List<MyEntity> resultList = entityManager.createQuery(query).getResultList();

Example with WHERE condition:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<MyEntity> query = cb.createQuery(MyEntity.class);
Root<MyEntity> root = query.from(MyEntity.class);
// creating a predicate for the condition "propertyName = value"
Predicate condition = cb.equal(root.get("propertyName"), "value");
// adding the predicate to the query
query.where(condition);
List<MyEntity> resultList = entityManager.createQuery(query).getResultList();

Example with JOIN:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<AnotherEntity> query = cb.createQuery(AnotherEntity.class);
Root<MyEntity> myRoot = query.from(MyEntity.class);
// performing JOIN with another entity
Join<MyEntity, AnotherEntity> anotherJoin = myRoot.join("anotherEntityProperty");
query.select(anotherJoin); // selecting another entity
List<AnotherEntity> resultList = entityManager.createQuery(query).getResultList();
What is Criteria API and how to use it in Java for… - sobes.tech