Java 一次相交于三个查询的基于JPA标准的查询
我想找到所有安装了“b”=500、“b”=501和“c”=2的“a”。 在Java 一次相交于三个查询的基于JPA标准的查询,java,sql,jpa,Java,Sql,Jpa,我想找到所有安装了“b”=500、“b”=501和“c”=2的“a”。 在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 whe
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
查询,然后取这三个查询的交点。
但是我现在必须使用基于JPA标准的查询,没有本地SQL
或JPQL
我们可以进行三种不同的基于JPA标准的查询:
返回一个“a”列表,其中“b”=500
返回一个“a”列表,其中“b”=501和
返回一个“a”的列表,其中“c”=2
然后过滤所有三个返回列表中出现的所有“a”。但这将花费太长时间,我们的数据库包含数百万个“a”条目…因此这是SQL中的一个解决方案:
这与JPA条件查询一样长,因此我只展示如何翻译最后一个存在
条件,这是最难的部分:
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]))));
Subquery Subquery=searchQuery.Subquery(表3.class);
Root fromTable3SubQuery=subQuery.from(Table3.class);
列表子限制=新建ArrayList();
Subquery subQueryForInExpression=searchQuery.Subquery(Table2.class);
Root fromTable2SubQuery=subQueryForInExpression.from(Table2.class)的子查询;
subQueryForInExpression.select(fromTable2SubQuery.get(ID)).where(criteriaBuilder.equal(fromTable2SubQuery.get(info_ID),root.get(ID));
add(criteriaBuilder.equal(fromTable3SubQuery.get(c),'2');
添加(criteriaBuilder.in(fromTable3SubQuery.get(ecu_id)).value(subQueryForInExpression));
添加(criteriaBuilder.exists)(subQuery.select(
fromTable3SubQuery.get(c))。其中(
toArray(新谓词[0]);
->这只表示最后一个存在的部分,它请求c='2'连接。其他的都是类似的,但是没有表达的子查询
部分…我想这个链接可以帮助你。您可以创建3个子查询,然后使用criteriaBuilder.exists(子查询)
谓词。这里的更多信息谢谢你们,我现在可以用三个子查询替换intersect
命令,这三个子查询与连接,其中和在SQL中存在。我现在将尝试在criteriaBuilder
中翻译这一点,并发布解决方案,如果它有效的话……我还没有JPA Criteria Queria解决方案,但是带有Exist子查询的SQL现在正在工作:这是我找到子查询forinPression
的解决方案的地方,在存在部分中的In
语句中需要使用以下选项: