0

I am trying to get max date using criteria builder in a subquery. But I am getting this error Required type: Expression Provided: Expression

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.

1 Answers1

0

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();
Yogesh
  • 715
  • 1
  • 7
  • 20
  • Still not wokring now I am getting this error java: method greatest in interface javax.persistence.criteria.CriteriaBuilder cannot be applied to given types; required: javax.persistence.criteria.Expression found: javax.persistence.criteria.Path reason: inferred type does not conform to upper bound(s) inferred: java.lang.Object upper bound(s): java.lang.Comparable super java.lang.Object>,java.lang.Object – Vishal Naik May 27 '23 at 04:51
  • I think it seems your date field is has data type other then Timestamp. – Yogesh May 27 '23 at 13:32
  • 1
    Solved it had to as() sq.select(cb.greatest(s2.get(Exam.end)).as(LocalDate.class)). Thanks for the help. – Vishal Naik May 28 '23 at 05:49