场景
我有一个实体Treatment
,它有两个FK:
@ManyToOne
@JoinColumn(name = "product_id", nullable = true)
private Product product;
@ManyToOne
@JoinColumn(name = "product2_id", nullable = true)
private Product product2;
此 Product
实体具有常规 id 属性作为 PK。
我想要什么:
我想查找任何产品 id 与给定产品 id 匹配的所有处理,在 native SQL 中,它会类似于:
select t.id, product_id,product2_id, p1.category_id,p2.category_id
from Treatment t
left join product p1 on t.product_id=p1.id
left join product p2 on t.product2_id=p2.id
where p1.category_id=17 or p2.category_id=17
到目前为止我所做的事情:
给定:
CriteriaQuery<Treatment> cr = cb.createQuery(Treatment.class);
Root<Treatment> root = cr.from(Treatment.class);
我的尝试是:
if (category != null ) {
Predicate predicate = cb.or(
cb.equal(root.get("product").get("category"), category),
cb.equal(root.get("product2").get("category"), category)
);
predicateList.add(predicate);
}
但它不起作用:它会得到两种产品不为空且至少其中一种符合类别条件的处理。
生成的查询是(清理它以使其可读后):
select
...
from treatment t
cross join product p1
cross join product p2
where t.product_id=p1.id
and t.product2_id=p2.id
and (p1.category_id=17 or p2.category_id=17)
order by t.id desc
最佳答案
尝试使用 From#join
构建路径,您可以在其中显式定义连接类型,例如:
Predicate predicate = cb.or(
cb.equal(root.join("product", JoinType.LEFT).get("category"), category),
cb.equal(root.join("product2", JoinType.LEFT).get("category"), category)
);
关于java - hibernate 标准生成器 : How to filter by a nullable entity attribute?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58082891/