I try to port a Java web application to the new Java 8 Date&Time API (using 'LocalDate' and 'LocalDateTime' types among others)
In Java 7, java.util.Date could be used in JPA2 criteria API to filter result sets on dates. Typically one would do this by adding a predicate e.g.
..
predicatesList.add(builder.between(from.get(AccountLog_.valueDate), fromDate, toDate));
..
Now JPA2 doesn't support the new Java 8 Date&Time API (LocalDate and LocalDateTime) yet. With own "Attribute Converters", working with entities can already be achieved as described in the blog http://www.thoughts-on-java.org/persist-localdate-localdatetime-jpa/
Now to my question: how can I use LocalDate and LocalDateTime in JPA2 criteria API in order to filter the result sets on LocalDate instead of Date? 'between' as used previously doesn't work for LocalDate instances.
With my LocalDateTimeConverter
, I just tried greaterThanOrEqualTo
and lessThan
to check for a LocalDateTime
range like
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Meal> query = cb.createQuery(Meal.class);
Root<Meal> m = query.from(Meal.class);
query.select(m);
query.where(
cb.greaterThanOrEqualTo(m.<LocalDateTime> get(Meal.FIELD_WHEN), cb.literal(begin)),
cb.lessThan(m.<LocalDateTime> get(Meal.FIELD_WHEN), cb.literal(end))
);
return em.createQuery(query).getResultList();
and even
cb.between(m.<LocalDateTime> get(Meal.FIELD_WHEN), cb.literal(begin), cb.literal(end))
works as expected. What exactly is causing trouble with your code? Maybe <LocalDateTime>
is missing?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With