Criteriabuilder在两列上相等

时间:2018-02-19 22:01:03

标签: java hibernate jpa jpa-criteria

使用Criteriabuilder编写查询时,如何在两列上添加相同的条件? e.g:

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:参数值[org.hibernate.jpa.criteria.path.SingularAttributePath@236f0ece]与预期类型[java.lang.String(n / a)]`

不匹配

1 个答案:

答案 0 :(得分:0)

您可以通过创建两个单独的“相等”谓词并使用这两个谓词来创建一个带有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();