JPA Criteria API:如何在嵌套集合中选择属性

时间:2011-04-14 02:49:30

标签: java jpa-2.0 criteria-api

我有一个班级CustomerCustomerDependant个实体。 Customer与其家属有多对多的双向关系。我需要找到按名称和从属名称过滤的客户。

在JPQL中做了类似的事情:

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

我如何使用JPA Criteria Queries做同样的事情?

1 个答案:

答案 0 :(得分:11)

取自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是一种联接,所以我猜你也可以尝试一下。