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

发布于 2024-11-01 04:27:33 字数 335 浏览 4 评论 0原文

我有一个类 CustomerCustomerDependant 实体。 客户与其依赖者具有多对多的双向关系。我需要找到按姓名和附属姓名过滤的客户。

它在 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?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

陈甜 2024-11-08 04:27:33

摘自 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

这是我在没有 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 是一种连接类型,所以我想您也可以尝试一下。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文