目前我有一个 java 应用程序正在查询 DB2 10.5 数据库并使用 JPA 2.0 作为包装器。我有一个有效的查询,可以很好地获取我需要的数据。但是,我需要第二个查询,除了添加动态参数之外,它与第一个查询完全相同。他们的查询足够大(并且有几个类似的查询),看起来像是大量的重复,基本上列出了相同的查询两次,但有一个包含额外的 where 条件,而另一个则不包含让我尝试给出我的查询。示例:
在我的 orm.xml 中(我们倾向于使用命名查询和命名 native 查询),我有以下命名查询:
select dates
from DateTable dates, Product p
where dates.id = p.id
and ... <multiple conditions etc>
我的第二个查询将与上面的完全相同,除了 将从代码中获取动态参数:
select dates
from DateTable, Product p
where dates.id = p.id
and p.id = :someDynamicIdHere
and ... <multiple conditions etc>
我想将它们合并到 JPA 可以理解的一个 orm.xml 定义中。需要明确的是,当 someDynamicIdHere 不为空时,我想添加额外的 where 条件“and p.id = :someDynamicIdHere”。我尝试过 CASE/WHEN/THEN/END 但我过去的使用仅用于列操作,而不是用于动态更新 where 子句。这可能吗?如果可以,语法是什么?谢谢你的帮助! -道格
最佳答案
使用条件 API:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Entity> cq = cb.createQuery(Entity.class);
Root<Entity> r = cq.from(Entity.class);
List<Predicate> p = new ArrayList<>();
//conditionally create zero or more conditions
Predicate condition= cb.equal(r.get("fieldName"), user.getId());
p.add(condition);
if(Collections.isNotEmpty(p)){
Predicate[] pArray = p.toArray(new Predicate[]{});
Predicate predicate = cb.and(pArray);
cq.where(predicate);
}
cq.orderBy(cb.desc(r.get("fieldName")));
return em.createQuery(cq).getResultList();
关于java - 如何在JPA/DB2中动态添加Where条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41173934/