【问题标题】:How to build a CriteriaQuery predicate IN clause with multiple columns?如何构建具有多列的 CriteriaQuery 谓词 IN 子句?
【发布时间】:2017-03-21 04:32:31
【问题描述】:

给定在CriteriaQuery 中使用的Predicate,例如这个:

Predicate predicate = root.get(MyTable.col1).in("col1Val1", "col1Val2");

这可以扩展为使用多个 AND 字段,例如和下面的SQL一样吗?

SELECT *
FROM MyTable
WHERE (col1, col2, col3) IN (
    ("col1Val1", "col2Val1", "col3Val1"),
    ("col1Val2", "col2Val2", "col3Val2")
);

【问题讨论】:

    标签: java mysql sql hibernate criteria


    【解决方案1】:

    不那么优雅的方法,使用 JPA 标准构建器

        Path<String> col1Path=root.get("col1");
        Path<String> col2Path=root.get("col2");
        Path<String> col3Path=root.get("col3");
    
        Predicate p0=criteriaBuilder.concat(col1Path,col2Path,col3Path)
             .in("col1Val1"||"col2Val1"||"col3Val1",
                  "col1Val2"|| "col2Val2"|| "col3Val2");
    

    第二种方法

        Path<String> col1Path=root.get("col1");
        Path<String> col2Path=root.get("col2");
        Path<String> col3Path=root.get("col3");
    
        Predicate p1=criteriaBuilder.or(
              criteriaBuilder.and(criteriaBuilder.equal(col1Path,"col1Val1"),
                                  criteriaBuilder.equal(col2Path,"col2Val1"),
                                  criteriaBuilder.equal(col3Path,"col3Val1") 
                                  ), 
              criteriaBuilder.and(criteriaBuilder.equal(col1Path,"col1Val2"),
                       criteriaBuilder.equal(col2Path,"col2Val2"),
                       criteriaBuilder.equal(col3Path,"col3Val2") 
                       )
               );
    

    【讨论】:

    • 感谢您的回答!第一种方法可能会遇到连接字符串不能唯一标识单个字符串的问题(例如,列值“col1Val1col2”、“Val1col3”和“Val1”也会匹配)。第二种方法似乎更好 - 但在我的情况下,将匹配一个非常大的值列表,所以我想知道性能将如何比较......
    • ...刚刚找到了上述问题的答案(但遗憾的是不是我想听到的):stackoverflow.com/questions/782915#2481458
    • 通常 IN 子句不是有效的,特别是对于大型比较集。似乎 JPA 不支持元组中的 where 子句,我试图准确地找到它,但我没有成功,但无论如何或 -和解决方案的作品,并具有与IN几乎相同的性能。如果您有大集合要比较,也许您可​​以找到一些更一般的条件
    猜你喜欢
    • 2011-02-20
    • 2021-12-07
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    相关资源
    最近更新 更多