In previous article, we took some introduction about criteria api in jpa and looked into a simple example about criteria api and compared with JPQL. This article deals with criteria api query roots.
Criteria API query roots
We have learned that in jpql, identification variables are used to create path expressions and access the properties of the entities. Criteria API query roots provide similar functionality. Simply said, Criteria API query roots correspond to an identification variable in JPQL.
Taking the example from introduction to criteria api,
JPQL is: SELECT t FROM Teacher t where t is the identification variable which can be used to access path expressions.
Criteria API is java programming and not simply JPQL strings. So the properties are accessed using objects. These objects are criteria api query roots objects. These can be created with the help of CriteriaQuery interface which can be obtained from CriteriaBuilder.
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Teacher> query = cb.createQuery(Teacher.class);
Root<Teacher> teacher = query.from(Teacher.class);
Let us understand what above lines of code mean
- CriteriaBuilder cb = em.getCriteriaBuilder(); Obtain CriteriaBuilder from the EntityManager .
- CriteriaQuery<Teacher> query = cb.createQuery(Teacher.class); Will create a query that will return the results of type Teacher entity.
- The from() method returns an instance of Root corresponding to the entity type.
- Root interface extends From interface which exposes functionality to joins.
- The From interface extends Path which further extends Expression and Selection .
I hope this article helped understand criteria api query roots. In next article, we will learn about criteria api path expressions.