本文介绍了CriteriaBuilder和& CriteriaBuilder.or,或如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试更改以下HQL以使用JPA标准:
I'm trying to change the following HQL to use JPA Criteria:
select distinct d from Department d
left join fetch d.children c
where d.parent is null
and (
d.name like :term
or c.name like :term
)
order by d.name
部门
有一个 Set<部门>
的孩子。
条件:
CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
CriteriaQuery<Department> c = cb.createQuery(Department.class);
Root<Department> root = c.from(Department.class);
root.fetch("children", JoinType.LEFT);
Path<Department> children = root.join("children", JoinType.LEFT);
c.orderBy(cb.asc(root.get("name")));
c.distinct(true);
c.where(cb.isNull(root.get("parent")));
String param = "%" + "term" + "%";
cb.and(cb.like(root.<String> get("name"), param));
cb.or(cb.like(children.<String> get("name"), param));
TypedQuery<Department> tq = getEntityManager().createQuery(c);
departments = tq.getResultList();
我知道这可能有点简洁,但是HQL返回24,而Criteria版本为28。认为我没有处理:
I know it can be a bit terse, however, the HQL returns 24 and Criteria version 28. I think I'm not handling:
and (x = y OR z = y)
正确。任何指针将不胜感激。
谢谢。
correctly. Any pointers will be greatly appreciated.Thanks.
推荐答案
这是JPQL查询的where子句:
Here's the where clause of your JPQL query:
where d.parent is null
and (
d.name like :term
or c.name like :term
)
where子句包含两个谓词:
The where clause contains two predicates:
d.parent is null
和
(d.name like :term
or c.name like :term)
第二个谓词是或
包含两个谓词:
The second predicate is an or
containing two predicates:
d.name like :term
和
c.name like :term
因此您的条件查询中需要相同的结构:
So you need the same structure in your criteria query:
Predicate orClause =
cb.or(cb.like(root.<String>get("name"), param),
cb.like(children.<String>get("name"), param));
c.where(cb.isNull(root.get("parent")),
orClause);
这篇关于CriteriaBuilder和& CriteriaBuilder.or,或如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!