JPA Criteria Builder中的If/Case语句 [英] If/Case statement in JPA Criteria Builder
问题描述
我想建立一个查询,该查询在不同实体上搜索日期.我的结构是:
I want to build up a query which search dates on different entites. My structure is:
- 合同有日期(不可为空)
- 员工有日期(不可为空)
- 员工可能具有合同ID(可以为空)
如果某位员工有合同,我想获取合同日期.如果员工没有合同,那么我想返回员工日期.
If a Employee has a contract I want to retrieve the contract date. If an employee does not have a contract then I want to return the Employee date.
到目前为止,我的代码是:
My code so far is:
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.
This does not seem to work though. I always appear to go into the isNull which I do not expect.
我很乐意对此进行更多研究,但我想我的问题是这是否是正确的解决方法.是吗?我在criteriaBuilder中也看到了selectCase,所以也许这可能是一个更好的解决方案.
I am happy to look into this some more but I guess my question is whether this is the correct way of going about it. Is it? I have seen a selectCase as well in criteriaBuilder so perhaps that may be a better solution.
任何指针都将得到很好的接收.
Any pointers would be greatly received.
谢谢
推荐答案
这是一个解决方案,不确定是否可行,但是我们将在您的帮助下设法使其起作用:):
Here would be a solution, not sure if it works, but we will manage to get it work with your help :):
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
,这样可以节省空间,并且我觉得更舒适.
I do not understand why use "inputDate" as Expression instead of a Date? Also, I suggest renaming criteria
to c
and criteriaBuilder
to cb
, this would save space and I think it is more comfortable.
这篇关于JPA Criteria Builder中的If/Case语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!