How to filter child collection in JPQL query?(如何在 JPQL 查询中过滤子集合?)
问题描述
我有以下数据库模型:
Category -< ProductCategory >- Product -< Variant
(Category 和 Product 是多对多关系,Product 和 Variant<是一对多关系/代码>)
(Category has many-to-many relationship with Product and Product has one-to-many relationship with Variant)
现在我需要获取所有 Category 记录,这些记录的产品具有 active 变体.我通过以下 JPQL 查询获取这些对象:
Now I need to get all Category records that have product with active variants. I'm getting these objects via the following JPQL query:
@Query("select distinct c from Category c join c.products as p join p.variants as pv where pv.active = true")
效果很好 - 准确返回类别 - 但是每个 Category 都包含 所有 产品 - 不仅 这些具有 active 变体.
It works well - returns categories accurately - however every single Category contains all the products - not only these with active variants.
如何过滤掉在单个查询中处于非活动状态的产品(或变体)?
How can I filter out the products (or variants) that are inactive in a single query?
这里是一个包含数据库结构和示例数据的 postgres 脚本.对于给定的数据,两个类别(CAT 1、CAT 2)、两个产品(PROD 1、PROD 2)并且应该返回三个变体(VAR 1、VAR 2、VAR 3).
Here's a postgres script that with database struct and sample data. For given data two categories (CAT 1, CAT 2), two products (PROD 1, PROD 2) and three variants (VAR 1, VAR 2, VAR 3) should be returned.
推荐答案
我遇到了完全相同的问题,我花了一段时间才弄清楚它是如何工作的.当您在 JOIN 之后添加 FETCH 时,应过滤子列表,如下所示:
I had exactly the same problem and it took me a while to find out how this works. The child list should be filtered when you add FETCH after your JOIN like this:
SELECT DISTINCT c FROM Category c JOIN FETCH c.products as p join p.variants as pv where pv.active = true
这篇关于如何在 JPQL 查询中过滤子集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 JPQL 查询中过滤子集合?
基础教程推荐
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
