The Criteria API is one of the most common ways of constructing queries for entities and their persistent state.
It is just an alternative method for defining JPA queries.
Criteria API defines a platform-independent criteria queries, written in Java programming language. It was introduced in JPA 2.0.
The main purpose behind this is to provide a type-safe way to express a query.
Steps to create Criteria Query: -
To create a Criteria query, follow the below steps: -
Step 1. Create an object of CriteriaBuilder interface by invoking getCriteriaBuilder() method on the instance of EntityManager interface.
EntityManager em = emf.createEntityManager();
CriteriaBuilder cb=em.getCriteriaBuilder();
Step 2. Now, build an instance of CriteriaQuery interface to create a query object.
CriteriaQuery<StudentEntity> cq=cb.createQuery(StudentEntity.class);
Step 3. Call from method on CriteriaQuery object to set the query root.
Root<StudentEntity> stud=cq.from(StudentEntity.class);
Step 4. Now, call the select method of CriteriaQuery Object to specify type of query result.
CriteriaQuery<StudentEntity> select = cq.select(stud);
Step 5. Create an instance of Query interface and specify the type of method used to access the database records
Query q = em.createQuery(select);
Step 6. Now, control the execution of query by calling the methods of Query Interface.
List<StudentEntity> list = q.getResultList();
Methods of Criteria API Query Clauses
Following is the list of clauses with the corresponding interface and methods.
Clause |
Criteria API Interface |
Methods |
SELECT |
CriteriaQuery |
select() |
FROM |
AbstractQuery |
from() |
WHERE |
AbstractQuery |
where() |
ORDER BY |
CriteriaQuery |
orderBy() |
GROUP BY |
AbstractQuery |
groupBy() |
HAVING |
AbstractQuery |
having() |
Note: - The CriteriaQuery interface is the sub-interface of AbstractQuery interface.