Introduction to the Criteria API

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

We have learned how JPQL can be used to query against the entities and retrieve the results in the form of entities. JPA provides an alternative to JPQL in the form of criteria api. Criteria API is a programmatic approach to query instead of string based approach as in JPQL.

The Criteria API:

In this example we will simply look at an example of criteria API and see how it differs from JPQL. If we want to select a Teacher whose first name is “prasad”, then JPQL query for it would be

Equivalent query in criteria API would be as follows.

Some points to be noted here are:

  • JPQL keywords SELECT, FROM, WHERE and LIKE have matching methods in the form of select(), from(), where() and like() in criteria api for CriteriaQuery.
  • CriteriaBuilder interface is obtained from EntityManager through the getCriteriaBuider() method. We have done it in our example using CriteriaBuilder cb = em.getCriteriaBuilder();
  • First use of CriteriaBuider interface is to create an instance of CriteriaQuery, we have done it as
  • CriteriaBuilder is also used to construct conditional expressions in where clause. Here, where(cb.equal(teacher.get("firstName"), "prasad")); demonstrates this.
  • All the conditional expression keywords, operators and functions from JPQL are represented in some manner in CriteriaBuilder interface in criteria api.
  • Declaring Root<Teacher> teacher is identical to declaring the identification variable in JPQL. This root object will be the basis of path expression in criteria api.

The query formed above can be executed using

This will give the result

Prasad Kharkar 20000

I hope this example gives a little introduction to jpa criteria api. In further articles, we will further look into criteria api.

 

References for further study :

Share Button

Prasad Kharkar

Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

3 thoughts on “Introduction to the Criteria API

Leave a Reply

Your email address will not be published. Required fields are marked *