JPA2标准和Java 8 Date& Time API [英] JPA2 Criteria and Java 8 Date&Time API

查看:337
本文介绍了JPA2标准和Java 8 Date& Time API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将Java Web应用程序移植到新的Java 8 Date& Time API(使用LocalDate和LocalDateTime类型)。

I try to port a Java web application to the new Java 8 Date&Time API (using 'LocalDate' and 'LocalDateTime' types among others)

在Java 7,java.util.Date可以在JPA2标准API中使用,以过滤日期结果集。通常,通过添加谓词,例如

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));
..

现在JPA2不支持新的Java 8 Date& Time API LocalDate和LocalDateTime)。使用自己的属性转换器,可以按照 http: //www.thoughts-on-java.org/persist-localdate-localdatetime-jpa/

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/

现在我的问题:如何使用LocalDate和LocalDateTime在JPA2标准API中,以过滤 LocalDate 而不是Date的结果集?

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.

推荐答案

使用我的 LocalDateTimeConverter

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();

甚至

cb.between(m.<LocalDateTime> get(Meal.FIELD_WHEN), cb.literal(begin), cb.literal(end))

按预期工作。究竟是什么导致你的代码的麻烦?可能< LocalDateTime> 缺少?

works as expected. What exactly is causing trouble with your code? Maybe <LocalDateTime> is missing?

这篇关于JPA2标准和Java 8 Date&amp; Time API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆