Define criteria in terms of Hibernate.
In Hibernate, criteria are used to create queries programmatically, allowing developers to build dynamic queries without writing HQL (Hibernate Query Language) or SQL directly. The Criteria API provides a way to construct queries using a more object-oriented approach, which can be particularly useful for complex queries or when the query structure needs to change based on user input or other conditions.
CriteriaBuilder: This is the starting point for creating a Criteria query. It provides methods to construct various parts of the query, such as selecting fields, defining predicates (conditions), and specifying ordering.
CriteriaQuery: This represents a specific query. It is created using the CriteriaBuilder
and defines the structure of the query, including the root entity and the selection criteria.
Root: This represents the entity that is being queried. It acts as the starting point for building the query and allows you to specify which entity's attributes you want to work with.
Predicate: This is used to define conditions in the query. Predicates can be combined using logical operators (AND, OR, NOT) to create complex conditions.
TypedQuery: After building the criteria query, you can create a TypedQuery
to execute the query and retrieve results.
Here’s a simple example of how to use the Criteria API in Hibernate:
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Predicate;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import java.util.List;
// Assuming you have an entity class named 'Employee'
public List<Employee> findEmployeesByDepartment(EntityManager entityManager, String department) {
// Step 1: Get the CriteriaBuilder
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
// Step 2: Create a CriteriaQuery
CriteriaQuery<Employee> criteriaQuery = criteriaBuilder.createQuery(Employee.class);
// Step 3: Define the root of the query
Root<Employee> root = criteriaQuery.from(Employee.class);
// Step 4: Define the predicates (conditions)
Predicate departmentPredicate = criteriaBuilder.equal(root.get("department"), department);
// Step 5: Set the where clause
criteriaQuery.select(root).where(departmentPredicate);
// Step 6: Create a TypedQuery and execute it
TypedQuery<Employee> query = entityManager.createQuery(criteriaQuery);
return query.getResultList();
}
The Criteria API in Hibernate is a powerful tool for building dynamic and type-safe queries. It abstracts the complexity of query construction and allows developers to work with Java objects rather than raw SQL, making it easier to maintain and understand the code.