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);
The Criteria API allows us to build up a criteria query object programmatically, where we can apply different kinds of filtration rules and logical conditions. Since Hibernate 5.2, the Hibernate Criteria API is deprecated, and new development is focused on the JPA Criteria API.
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.
Below is the pseudo-code for using sub-query using Criteria API. CriteriaBuilder criteriaBuilder = entityManager. getCriteriaBuilder(); CriteriaQuery<Object> criteriaQuery = criteriaBuilder. createQuery(); Root<EMPLOYEE> from = criteriaQuery.
It gives you access to the employee referenced by the main query so you can use it and its tables in the subquery
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With