gpt4 book ai didi

jpa-2.0 - CriteriaBuilder.and & CriteriaBuilder.or,操作方法?

转载 作者:行者123 更新时间:2023-12-03 22:53:40 24 4
gpt4 key购买 nike

我正在尝试更改以下 HQL 以使用 JPA 标准:

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
Department有一个 Set<Department> child 的。

标准:
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。我想我没有处理:
and (x = y OR z = y)

正确。任何指针将不胜感激。
谢谢。

最佳答案

这是 JPQL 查询的 where 子句:

where d.parent is null 
and (
d.name like :term
or c.name like :term
)

where 子句包含两个谓词:
d.parent is null 


(d.name like :term 
or c.name like :term)

第二个谓词是 or包含两个谓词:
d.name like :term


c.name like :term

因此,您的标准查询中需要相同的结构:
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);

关于jpa-2.0 - CriteriaBuilder.and & CriteriaBuilder.or,操作方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18069449/

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