如何构建具有多列的 CriteriaQuery 谓词 IN 子句?
How to build a CriteriaQuery predicate IN clause with multiple columns?
给定一个 Predicate
used in a CriteriaQuery
,例如这个:
Predicate predicate = root.get(MyTable.col1).in("col1Val1", "col1Val2");
是否可以将其扩展为使用多个 ANDed 字段,例如和下面的SQL一样吗?
SELECT *
FROM MyTable
WHERE (col1, col2, col3) IN (
("col1Val1", "col2Val1", "col3Val1"),
("col1Val2", "col2Val2", "col3Val2")
);
不太优雅的方法,使用 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")
)
);
给定一个 Predicate
used in a CriteriaQuery
,例如这个:
Predicate predicate = root.get(MyTable.col1).in("col1Val1", "col1Val2");
是否可以将其扩展为使用多个 ANDed 字段,例如和下面的SQL一样吗?
SELECT *
FROM MyTable
WHERE (col1, col2, col3) IN (
("col1Val1", "col2Val1", "col3Val1"),
("col1Val2", "col2Val2", "col3Val2")
);
不太优雅的方法,使用 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")
)
);