The Criteria API is a predefined API used to define queries for entities. It is the alternative way of defining a JPQL query. These queries are type-safe, and portable and easy to modify by changing the syntax. Similar to JPQL it follows abstract schema (easy to edit schema) and embedded objects. The metadata API is mingled with criteria API to model persistent entity for criteria queries.
The major advantage of the criteria API is that errors can be detected earlier during compile time. String based JPQL queries and JPA criteria based queries are same in performance and efficiency.
History of criteria API
The criteria API is included into all versions of JPA therefore each step of criteria API is notified in the specifications of JPA.
- In JPA 2.0, the criteria query API, standardization of queries are developed.
- In JPA 2.1, Criteria update and delete (bulk update and delete) are included.
Criteria Query Structure
The Criteria API and the JPQL are closely related and are allowed to design using similar operators in their queries. It follows javax.persistence.criteria package to design a query. The query structure means the syntax criteria query.
The following simple criteria query returns all instances of the entity class in the data source.
EntityManager em = ...; CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Entity class> cq = cb.createQuery(Entity.class); Root<Entity> from = cq.from(Entity.class); cq.select(Entity); TypedQuery<Entity> q = em.createQuery(cq); List<Entity> allitems = q.getResultList();
The query demonstrates the basic steps to create a criteria.
- EntityManager instance is used to create a CriteriaBuilder object.
- CriteriaQuery instance is used to create a query object. This query object’s attributes will be modified with the details of the query.
- CriteriaQuery.from method is called to set the query root.
- CriteriaQuery.select is called to set the result list type.
- TypedQuery<T> instance is used to prepare a query for execution and specifying the type of the query result.
- getResultList method on the TypedQuery<T> object to execute a query. This query returns a collection of entities, the result is stored in a List.