java JPA Criteria API:如何在嵌套集合中选择属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5658010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JPA Criteria API: How to select property in nested collection
提问by Otávio Garcia
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.
我有一个类Customer
和CustomerDependant
实体。Customer
与其依赖项具有多对多的双向关系。我需要查找按名称和相关名称过滤的客户。
It's done something like this in JPQL:
它在 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?
我如何使用 JPA Criteria Queries 做同样的事情?
回答by Edwin Dalorzo
Taken from JPA Specification section 6.5.4
取自 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);
This query is equivalent to the following Java Persistence query language query:
此查询等效于以下 Java Persistence 查询语言查询:
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.
Fetch 是一种连接,所以我想你也可以尝试一下。