Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA2 Criteria and Java 8 Date&Time API

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.

like image 973
Hubert Schumacher Avatar asked Jan 30 '16 11:01

Hubert Schumacher


1 Answers

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?

like image 182
Steffen Harbich Avatar answered Sep 28 '22 05:09

Steffen Harbich