如何为下面给定的JPQL查询编写criteria builder api查询?我正在使用JPA 2.2
。
SELECT *
FROM Employee e
WHERE e.Parent IN ('John','Raj')
ORDER BY e.Parent
发布于 2017-03-01 20:15:24
这个标准设置应该可以做到这一点:
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Employee> q = cb.createQuery(Employee.class);
Root<Employee> root = q.from(Employee.class);
q.select(root);
List<String> parentList = Arrays.asList(new String[]{"John", "Raj"});
Expression<String> parentExpression = root.get(Employee_.Parent);
Predicate parentPredicate = parentExpression.in(parentList);
q.where(parentPredicate);
q.orderBy(cb.asc(root.get(Employee_.Parent));
q.getResultList();
我在这里使用了重载的CriteriaQuery.where
方法,它接受一个Predicate
。本例中为in
谓词。
发布于 2019-01-24 04:51:53
您也可以使用Criteria API In子句来执行此操作,如下所示:
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Employee> cq = cb.createQuery(Employee.class);
Root<Employee> root = cq.from(Employee.class);
List<String> parentList = Arrays.asList("John", "Raj");
In<String> in = cb.in(root.get(Employee_parent));
parentList.forEach(p -> in.value(p));
return entityManager
.createQuery(cq.select(root)
.where(in).orderBy(cb.asc(root.get(Employee_.Parent)))
.getResultList();
请查看我的Github,了解这一点以及几乎所有可能的标准示例。
发布于 2020-04-30 21:38:28
List<String> parentList = Arrays.asList("John", "Raj");
final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
final CriteriaQuery<Employee> query = cb.createQuery(Employee.class);
final Root<Employee> employee = query.from(Employee.class);
query.select(employee).where(employee.get("Parent").in(parentList));
这应该可以很好地工作。有关更多信息,请参考baeldung的这篇文章。它是非常足智多谋的https://www.baeldung.com/jpa-criteria-api-in-expressions
https://stackoverflow.com/questions/42530677
复制相似问题