JPA Criteria API: How to select property in nested collection

Otávio Garcia picture Otávio Garcia · Apr 14, 2011 · Viewed 14.4k times · Source

I have a class Customer and CustomerDependant entities. Customer has many to many bi-directional relationship with its dependents. I need to find customers filtering by name and dependent name.

It's done something like this in JPQL:

select c join fetch c.dependants d from Customer c where c.name like
'foo' and d.name like 'foo'

How I can do the same thing with JPA Criteria Queries?

Answer

Edwin Dalorzo picture Edwin Dalorzo · Apr 14, 2011

Taken from JPA Specification section 6.5.4

CriteriaQuery<Department> q = cb.createQuery(Department.class);
Root<Department> d = q.from(Department.class);
d.fetch(Department_.employees, JoinType.LEFT);
q.where(cb.equal(d.get(Department_.deptno), 1)).select(d);

This query is equivalent to the following Java Persistence query language query:

SELECT d
FROM Department d LEFT JOIN FETCH d.employees
WHERE d.deptno = 1

This is what I do it without fetch

CriteriaQuery<Department> q = cb.createQuery(Department.class);
Root<Department> dept = q.from(Department.class);
Join<Department,Employee> emp = d.join(Department_.employees);
q.where(cb.equal(emp.get(Employee_.name),"edalorzo"));

Fetch is a type of join, so I guess you could experiment with that too.