I want to build up a query which search dates on different entites. My structure is:
- Contract has date (non nullable)
- Employee has date (non nullable)
- Employee may have a contract id (nullable)
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) ));}
This does not seem to work though. I always appear to go into the isNull which I do not expect.
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.
Thanks
I think what you want to do is use
Case<Date>
, and usePredicate
only as first argument toCase#when
.Case<Date>
is anExpression<Date>
, which is what you want to pass intoCriteriaQuery#multiselect
.Here would be a solution, not sure if it works, but we will manage to get it work with your help :):
I do not understand why use "inputDate" as Expression instead of a Date? Also, I suggest renaming
criteria
toc
andcriteriaBuilder
tocb
, this would save space and I think it is more comfortable.