This tutorial will show you how to use JPA(Java Persistence API) Criteria Queries for selecting data from database.
The Java Persistence API (JPA) is a Java specification for accessing, persisting, and managing data between Java objects / classes and a relational database.
The Criteria API is used to define queries for entities and their persistent state by creating query-defining objects. Criteria queries are written using Java programming language APIs, are typesafe, and are portable. Such queries work regardless of the underlying data store. The major advantage of Criteria API is that errors can be detected earlier during the compile time. String-based JPQL(Java Persistence Query Language) queries and JPA criteria based queries are same in performance and efficiency.
Steps to create Criteria Query
1. EntityManager instance is used to create a CriteriaBuilder object.
2. CriteriaQuery instance is used to create a query object from CriteriaBuilder object. The attributes of this object will be modified with the details of the query.
3. CriteriaQuery.form method is called to set the Root of the query.
4. CriteriaQuery.select is called to set the result list type for a particular POJO class mapped to a database table.
5. TypedQuery<T> instance is used to prepare a query for execution and specifying the type of the query result.
6. getResultList method is used on the TypedQuery<T> object for executing a query to return the result list of a collection of entities.