简体   繁体   中英

JPA Criteria API: How to select property in nested collection

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM