【问题标题】:How Do I Add A Where Condition Dynamically In JPA/DB2如何在 JPA/DB2 中动态添加 Where 条件
【发布时间】:2016-12-15 21:51:52
【问题描述】:

目前我有一个查询 DB2 10.5 数据库并使用 JPA 2.0 作为包装器的 java 应用程序。我有一个有效的查询,可以很好地获取我需要的数据。但是,我需要第二个查询,它与第一个查询完全相同,只是添加了一个动态参数。他们的查询足够大(并且有几个类似的查询),基本上两次列出相同的查询似乎有很多重复,但有一个包含额外的 where 条件,而另一个不包含示例:

在我的 orm.xml 中(我们倾向于使用命名查询和命名本机查询)我有以下命名查询:

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 条件“和 p.id = :someDynamicIdHere”。我已经尝试过 CASE/WHEN/THEN/END,但我过去只用于列操作,而不是动态更新 where 子句。这可能吗?如果可以,语法是什么?谢谢你的帮助! -道格

【问题讨论】:

  • 如果你想动态生成一个查询,就去做吧。 Java 可以很好地做到这一点。然而,XML 不能。所以不要放在orm.xml中,而是放在Java代码中。

标签: java jpa db2


【解决方案1】:

使用标准 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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    • 2023-01-17
    • 1970-01-01
    • 1970-01-01
    • 2012-07-26
    • 2017-03-25
    • 1970-01-01
    相关资源
    最近更新 更多