Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA find entities where date is between start and end date that can be null using Criteria

CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery cQuery = builder.createQuery();
    Root<AcsTemplateDateJPA> root = cQuery.from(AcsTemplateDateJPA.class);
    ParameterExpression<Date> d = builder.parameter(Date.class);
    cQuery.where(builder.between(d, root.<Date>get("inservicedate"), root.<Date>get("outservicedate"))); 
    Query query = em.createQuery(cQuery.select(root.get("acstemplateid"))).setParameter(d, planDate, TemporalType.DATE);
    List results =query.getResultList(); 

here outService date can be null (the end is infinitely in the future) how i can add this condition?

Thanks,

like image 455
user2190192 Avatar asked Jan 14 '23 20:01

user2190192


1 Answers

I would split the date comparison in two blocks, and test if outservicedate isNull(). Something like:

Predicate startPredicate = builder.greaterThanOrEqualTo(root.<Date>get("inservicedate"), d);
Path<Date> outServiceDate = root.<Date>get("outservicedate");
Predicate endPredicate = builder.or(builder.isNull(outServiceDate), builder.lessThanOrEqualTo(outServiceDate, d));
Predicate finalCondition = builder.and(startPredicate, endPredicate);
like image 97
perissf Avatar answered Apr 27 '23 08:04

perissf