Add CriteriaBuilder.between(Date) to Predicate?

后端 未结 3 1451
粉色の甜心
粉色の甜心 2021-01-13 23:30

I am new to JPA

I am trying to query a table where my input date value should be between the startDate and endDate of the database record

I am trying to do:<

相关标签:
3条回答
  • 2021-01-14 00:17

    Try this:

    criteriaBuilder.between(criteriaBuilder.literal(inputDate),
                            root.<Date>get("startDate"), 
                            root.<Date>get("endDate"));
    
    0 讨论(0)
  • 2021-01-14 00:28

    Something like this should work...

    List<Predicate> conditionsList = new ArrayList<Predicate>();
    Predicate onStart = criteriaBuilder.greaterThanOrEqualTo(root.get("startDate"), inputDate);
    Predicate onEnd = criteriaBuilder.lessThanOrEqualTo(root.get("endDate"), inputDate);
    conditionsList.add(onStart);
    conditionsList.add(onEnd);
    criteriaQuery.select(root).where(conditionsList.toArray(new Predicate[]{}));
    
    0 讨论(0)
  • 2021-01-14 00:30

    You can try this way.

    
        Predicate date =  cb.between(root.get("date"), dateBefore, dateAfter);
        predicate.add(date);
    
    

    this way works for my case.

    But for your case (using ParameterExpression).

    
        return entityManager.createQuery(query)
        .setParameter(d, currentDate, TemporalType.DATE).getResultList(); 
    
    

    When you create the query you set parameters. currentDate is your date, d is ParameterExpression that you create before.

    I prefer the first way, it is more intuitive and logical for me.

    0 讨论(0)
提交回复
热议问题