繁体   English   中英

如果/ Case语句在JPA Criteria Builder中

[英]If/Case statement in JPA Criteria Builder

我想建立一个查询,搜索不同的entites日期。 我的结构是:

  • 合同有日期(不可为空)
  • 员工有日期(不可为空)
  • 员工可能有合同ID(可空)

如果员工有合同我想要检索合同日期。 如果员工没有合同,那么我想退回员工日期。

到目前为止我的代码是:

if (inputDate!= null) {
    ParameterExpression<Date> exp = criteriaBuilder.parameter(Date.class, "inputDate");
    criteria.add(criteriaBuilder.or(
        criteriaBuilder.isNull(employee.get("contract")),
        criteriaBuilder.lessThanOrEqualTo(employee.<Date>get("creationDate"), exp),   criteriaBuilder.lessThanOrEqualTo((employee.join("contract").<Date>get("fromDate")), exp) ));}

这似乎不起作用。 我似乎总是进入我不期望的isNull。

我很高兴再看一下,但我想我的问题是这是否是正确的方法。 是吗? 我在criteriaBuilder中也看到了一个selectCase,所以也许这可能是一个更好的解决方案。

任何指针都会受到极大的欢迎。

谢谢

这将是一个解决方案,不确定它是否有效,但我们将设法让你的帮助:):

ParameterExpression<Date> inputDateExp = criteriaBuilder.parameter(Date.class, "inputDate");
Predicate employeeCreationDate = criteriaBuilder.lessThanOrEqualTo(
        employee.<Date>get("creationDate"), inputDateExp);
Predicate contractStartDate = criteriaBuilder.lessThanOrEqualTo(
        employee.join("contract").<Date>get("fromDate"), inputDateExp);

criteria.add(
        criteriaBuilder.selectCase().when(employee.get("contract").isNull(), employeeCreationDate).otherwise(contractStartDate));

我不明白为什么使用“inputDate”作为Expression而不是Date? 另外,我建议重命名criteria ,以ccriteriaBuildercb ,这样可节省空间,我认为这是更舒适。

我想你想要做的是使用Case<Date> ,并且只使用Predicate作为Case#when第一个参数。 Case<Date>是一个Expression<Date> ,这是你想要传递给CriteriaQuery#multiselect

CriteriaQuery<Employee> query = criteriaBuilder.createQuery(Employee.class);
Root<Employee> employee = query.from(Employee.class);
query.multiselect
(
    criteriaBuilder.selectCase()
        .when(criteriaBuilder.isNull(employee.get("contract")), employee.get("creationDate"))
        .otherwise(employee.join("contract").get("fromDate"))
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM