Search code examples
jpajpa-2.0criteriacriteria-api

Criteria API correlate


I have been Googling but do not understand what the consequence of calling the method correlate of javax.persistence.criteria.Subquery en the Criteria API.

http://www.objectdb.com/api/java/jpa/criteria/Subquery/correlate_CollectionJoin_

This is from the book Pro JPA2 Mastering the Java Persistence API.

When creating the criteria API query definition for this query, we must correlate the employees attribute of Project and then join it to the direct reports in order to calculate the average salary. This example also demonstrates the use of the type() method of the Path interface in order to do a polymorphic comparison of types:

CriteriaQuery<Project> c = cb.createQuery(Project.class);
Root<Project> project = c.from(Project.class);
Join<Project,Employee> emp = project.join("employees");
Subquery<Number> sq = c.subquery(Number.class);
Join<Project,Employee> sqEmp = sq.correlate(emp);
Join<Employee,Employee> directs = sqEmp.join("directs");
c.select(project)
 .where(cb.equal(project.type(), DesignProject.class),
        cb.isNotEmpty(emp.<Collection>get("directs")),
        cb.ge(sq, cb.parameter(Number.class, "value")));

What does this line do?
Join sqEmp = sq.correlate(emp);


Solution

  • It gives you access to the employee referenced by the main query so you can use it and its tables in the subquery