gpt4 book ai didi

java - 基于 JPA Criteria 的查询,一次与三个查询相交

转载 作者:行者123 更新时间:2023-12-01 17:56:20 25 4
gpt4 key购买 nike

我想找到所有安装了“b”= 500、“b”= 501 和“c”= 2 的“a”。 my three tables

SQL中我会这样做:

select a from table1 where id in (select info_id from table2 where b = '500')
intersect
select a from table1 where id in (select info_id from table2 where b = '501')
intersect
select a from table1 where id in (select info_id from table2 where id in (select ecu_id from table3 where c = '2'));

因此,我将创建三个 SQL 查询,然后取这 3 个查询的交集。但我现在必须使用基于 JPA 标准 的查询,而不是 native SQLJPQL

我们可以执行三个不同的基于 JPA 标准 的查询:

返回“a”列表,其中“b”= 500,

返回“a”列表,其中“b”= 501 且

返回“a”列表,其中“c”= 2。

然后过滤所有三个返回列表中出现的所有“a”。但这需要太长时间,我们的数据库包含数百万个“a”条目......

最佳答案

这是 SQL 中的一种解决方案: http://tpcg.io/mV3rZ2Of

这作为 JPA Criteria 查询非常长,因此我只展示如何翻译最后一个 Exists 条件,这是最难的部分:

Subquery<Table3> subQuery = searchQuery.subquery(Table3.class);
Root<Table3> fromTable3SubQuery = subQuery.from(Table3.class);
List<Predicate> subRestrictions = new ArrayList<>();

Subquery<Table2> subQueryForInExpression = searchQuery.subquery(Table2.class);
Root<Table2> fromTable2SubQuery = subQueryForInExpression.from(Table2.class);
subQueryForInExpression.select(fromTable2SubQuery.get(ID)).where(criteriaBuilder.equal(fromTable2SubQuery.get(info_id), root.get(ID)));

subRestrictions.add(criteriaBuilder.equal(fromTable3SubQuery.get(c), '2'));
subRestrictions.add(criteriaBuilder.in(fromTable3SubQuery.get(ecu_id)).value(subQueryForInExpression));

restrictions.add(criteriaBuilder.exists(subQuery.select(
fromTable3SubQuery.get(c)).where(
subRestrictions.toArray(new Predicate[0]))));

-> 这仅代表最后一个 Exists 部分,它要求 c = '2' 连接。其他类似,但没有 subQueryForInExpression 部分...

关于java - 基于 JPA Criteria 的查询,一次与三个查询相交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60709722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com