Error using criteriaBuilder.max() for LocalDate

741 Views Asked by At

I am trying to get max date using criteria builder in a subquery. But I am getting this error

Required type: Expression <LocalDate>
Provided: Expression <Number>

This is my code:

Subquery<LocalDate> subRoot = criteriaQuery.subquery(LocalDate.class);
subRoot.select(criteriaBuilder.max(root.get("date")));

I am trying to get max date from sub query which is required in my parent query.

2

There are 2 best solutions below

3
Yogesh On

Instead of max you have to use greatest for dates. Max is for Numeric types. refer below piece of code for reference

EntityManger em;      //to be injected or constructed

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Exam> cq = cb.createQuery(Exam.class);
Subquery<Date> sq = cq.subquery(Date.class);
Root<Exam> s1 = cq.from(Exam.class);
Root<Exam> s2 = sq.from(Exam.class);
sq.select(cb.greatest(s2.get(Exam.end)));
List<Exam> result = em.createQuery(cq).getResultList();
0
RamChandra Ali On

This should work too:

sq.select(cb.max(s2.get(Exam.end)).as(LocalDate.class)));