【问题标题】:JPA Criteria : in clause with many columnsJPA 标准:in 子句有很多列
【发布时间】:2016-09-08 12:13:14
【问题描述】:

我正在尝试使用 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


    【解决方案1】:

    另一种方法是使用字段连接

    创建一个方法,返回要在 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)
    

    【讨论】:

      【解决方案2】:

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

      参考:query for select which multiple values in the “IN” clause

      【讨论】:

      • 感谢您的回答。由于我不想使用本机查询,我用丑陋的类别和优先级列的值串联替换了许多列部分,但我有点失望。
      • 请提交 JPA 规范请求。
      猜你喜欢
      • 2021-10-15
      • 2014-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多