我想建立一个查询来搜索不同实体的日期。我的结构是:
- 契约(Contract)有日期(不可为空)
- 员工有日期(不可为空)
- 员工可能有契约(Contract)编号(可为空)
如果员工有契约(Contract),我想检索契约(Contract)日期。如果员工没有契约(Contract),那么我想返回员工日期。
到目前为止我的代码是:
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”作为表达式而不是日期?另外,我建议将 criteria
重命名为 c
并将 criteriaBuilder
重命名为 cb
,这样可以节省空间,我认为是更舒服。
关于java - JPA Criteria Builder 中的 If/Case 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10236445/