2

I have the following Hibernate 3.x Criteria Query which I want to convert it to a Hibernate JPA 2.0 query:

Calendar calLo = new GregorianCalendar();
calLo.set(Calendar.HOUR_OF_DAY, 00);
calLo.set(Calendar.MINUTE, 00);
calLo.set(Calendar.SECOND, 00);
Calendar calHi = new GregorianCalendar();
calHi.set(Calendar.HOUR_OF_DAY, 23);
calHi.set(Calendar.MINUTE, 59);
calHi.set(Calendar.SECOND, 00);

List taskList = session.createCriteria(Task.class, "task").add(Restrictions.ge("task.taskDate", calLo.getTime())).add(Restrictions.le("task.taskDate", calHi.getTime())).add(Restrictions.eq("task.taskActive", true)).addOrder(Order.desc("task.taskNo")).list();

I attempt to re-werite the code starting like:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery(Task.class);
Root task = cq.from(Task.class);
cq.select(task).where(cb.ge("task.taskDate", calLo.getTime()) ... );

But JPA 2 criteria queries do not seem to support CriteriaBuilder.ge(...) method to accept dates or calendars as input parameters and my code seems to fail from the start.

I need advice to retain and adapt the functionality of the Hibernate session criteria.

Skyhan
  • 871
  • 3
  • 15
  • 26

1 Answers1

6

As the javadoc indicates, the ge() method is for numbers. Use greaterThanOrEqualTo(), which accepts any Comparable.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • I made the above work, but got stuck in a similar problem with the following and do not understand why: `cq.select(kme).where(cb.equal(kme.get("mcode"), mcode.getTheCode()), cb.greaterThanOrEqualTo(kme.get("daDate"), someJavaUtilDate));` with an error saying 'no suitable method found for greaterThanEqualTo(javax.persistence.criteria.Path, java.util.Date) – Skyhan Mar 21 '12 at 09:25
  • 1
    You need to use `kme.get("daDate")` to have the first argument in the appropriate type. Or preferrably, use the generated metamodel classes rather than Strings. – JB Nizet Mar 21 '12 at 09:56