开发者

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 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜