2011-04-14 92 views
9

我有一個類CustomerCustomerDependant實體。 Customer與其家屬有多方面的許多雙向關係。我需要找到按名稱和相關名稱過濾的客戶。JPA Criteria API:如何選擇嵌套集合中的屬性

它做了這樣的事情在JPQL:

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

我如何做同樣的事情與JPA標準的查詢?

回答

10

從JPA規範剖面中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); 

此查詢等同於以下Java持久化查詢語言查詢:

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

這是我做沒有取

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是一種連接,所以我想你也可以嘗試一下。