JPA 标准:在具有多列的子句中

问题描述 投票:0回答:3

我正在尝试使用 JPA Criteria API 编写以下 SQL 查询

SELECT * FROM Table1 a
WHERE (a.category, a.priority) IN (
SELECT a1.category, max(a1.priority) FROM Table1 a1 GROUP BY a1.category
)

从功能上讲,查询选择 Table1 中每个类别具有最高优先级的元素。

categoryPriority = // defines the pair category/priority
mySubQuery = // defines the subquery
query.where(categoryPriority.in(mySubQuery)

这就是我正在寻找的示意图。

定义子查询不是问题,因为它有详细的文档记录。

但是我找不到一种方法来定义这对夫妇(a.category,a.priority)。

jpa criteria-api in-clause
3个回答
6
投票

JPA 中未提供

IN
子句中的多列。我认为您需要使用本机查询。

参考:查询选择“IN”子句中的多个值


2
投票

另一种方法是使用字段串联

创建一个方法,返回您想要在 DTO/实体中搜索的两个字段。

  public String getField1Field2Concatenated() {
    return field1+ field2;
  }


List<String> ids = list.stream().map(r -> r.getField1Field2Concatenated()).collect(Collectors.toList());

您可以连接两个字段并进行搜索。

Select e from Entity e where concat(e.field1,  c.field2) in (:ids)

如果任何字段不是文本,您可以投射

Select e from Entity e where concat(cast(c.field1 as string),  c.field2) in (:ids)

0
投票

就像我在提到这篇 Stackoverflow 帖子的 Discourse 问题中回答的那样,JPA 的 Hibernate 扩展

CriteriaBuilder
HibernateCriteriaBuilder
,它为您提供了或多或少稳定的 API。我的观点可能是错的,但我认为元组比较还不够稳定,这就是为什么此功能仅在
NodeBuilder
上定义,这是根据孵化的 SQM API 定义的。 您可以使用
NodeBuilder.tuple(null, root.get("attr1"), root.get("attr2")).in(subquery)
根据 JPA Criteria API 来建模相同的事物。

© www.soinside.com 2019 - 2024. All rights reserved.