gpt4 book ai didi

java - Criteriabuilder 在两列上相等

转载 作者:行者123 更新时间:2023-11-30 06:17:36 25 4
gpt4 key购买 nike

使用 Criteriabuilder 编写查询时,如何在两列上添加相等条件?例如:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<MyTable> root = cq.from(MyTable.class);
Predicate cond = cb.equal(root.get(MyTable_.columnA), root.get(MyTable_.columnB));

执行上述操作会导致异常:

java.lang.IllegalArgumentException: Parameter value [org.hibernate.jpa.criteria.path.SingularAttributePath@236f0ece] did not match expected type [java.lang.String (n/a)]`

最佳答案

您可以通过创建 2 个单独的“相等”谓词并使用这两个谓词通过 criteriaBuilder.and(predicate1, predicate2); 创建一个新谓词来实现此目的

您的查询应如下所示:

//Sample values to use in where clause
String columnATest = "Jimmy";
String columnBTest = "18";

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
//This will return a list of MyTable objects.
CriteriaQuery<MyTable> cq = cb.createQuery(MyTable.class);
Root<MyTable> root = cq.from(MyTable.class);
Predicate cond = null;

//If both columns should match the test values
cond = cb.and(cb.equal(root.get(MyTable_.columnA), columnATest), cb.equal(root.get(MyTable_.columnB), columnBTest));

//If only one of the 2 columns should match the test values
cond = cb.or(cb.equal(root.get(MyTable_.columnA), columnATest), cb.equal(root.get(MyTable_.columnB), columnBTest));

CriteriaQuery cq = criteriaQuery.select(root).where(cond);
TypedQuery typedQuery = entityManager.createQuery(cq);
List<MyTable> results = (List<MyTable>) typedQuery.getResultList();

关于java - Criteriabuilder 在两列上相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48874856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com