Skip to Content

Solved: What is the purpose of the criteria query and Root class in hibernate

Question

The following is a code that is written to execute a criteria query in hibernate, which will return all the rows with marks > 90:

CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<Student> criteriaQuery = criteriaBuilder.createQuery(Student.class);
Root<Student> root = criteriaQuery.from(Student.class);
criteriaQuery.select(root).where(criteriaBuilder.gt(root.get("marks"),90));

Query query = session.createQuery(criteriaQuery);
System.out.println(query.getResultList());

What exactly this Root class is for. I read somewhere that a criteria query forms a tree with nodes. But what are those nodes, how does it form a tree, and what does it do with it?

Answer

A root is simply an entity, from which all other types are reached by navigation. Think of the root as an inverted (real life) tree, where the root is on top and the branches/leaves are at the bottom. On top you only have one element (in a query you might have more than one root though, the effect of which is to create a cartesian product between all roots) and as you traverse the tree you get more elements.

So if you have a Student entity, and the student has inside it another two entities Grades and AcademicRecords, then the code:

Root<Student> root = criteriaQuery.from(Student.class);

will create a root Student, and then you can navigate the student to reach the Grades and AcademicRecords. You have a root node, the Student, and two “leaf” nodes, Grades and AcademicRecords. If any of the Grades or AcademicRecords have more entities inside them then you reach them from there, creating more nodes.

The JPA2 specification (section 6.5.2) states for roots:

A CriteriaQuery object defines a query over one or more entity, embeddable, or basic abstractschema types. The root objects of the query are entities, from which the other types are reached by nav-
igation. A query root plays a role analogous to that of a range variable in the Java Persistence query lan-
guage and forms the basis for defining the domain of the query.

A query root is created and added to the query by use of the from method of the AbstractQuery
interface (from which both the CriteriaQuery and Subquery interfaces inherit). The argument to
the from method is the entity class or EntityType instance for the entity. The result of the from
method is a Root object. The Root interface extends the From interface, which represents objects that
may occur in the from clause of a query.

A query may have more than one root. The addition of a query root has the semantic effect of creating a
cartesian product between the entity type referenced by the added root and those of the other roots

In the example above the Student class is the root entity and the Grades and AcademicRecords are the types that are reached by navigation.