JPA2 Criteria and Java 8 Date&Time API

£可爱£侵袭症+ 提交于 2019-12-05 21:18:50

问题


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.


回答1:


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?



来源:https://stackoverflow.com/questions/35101366/jpa2-criteria-and-java-8-datetime-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!