使用JPA标准查询比较两个日期之间的差异 [英] Compare difference between two dates using JPA Criteria Query

查看:2183
本文介绍了使用JPA标准查询比较两个日期之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MySQL作为应用程序的后端.

I am using MySQL as a backend for my application.

我想在下面使用JPA标准查询执行查询.

I want to execute query below using JPA Criteria Query.

SELECT * 
FROM table1 t1
WHERE datediff(now(), t1.created) >= 20;

注意:created的类型为TIMESTAMP

我想要条件查询,例如:

I want Criteria Query like:

CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();

// select
CriteriaQuery<Table1> query = cb.createQuery(Table1.class);

// from
Root<Table1> root = query.from(Table1.class);

// where
List<Predicate> predicates = new ArrayList<Predicate>();

// TODO: add expression for datediff(now(), t1.created) >= 20

query.where(cb.and(predicates.toArray(new Predicate[0])));

有人可以帮忙吗?

谢谢.

推荐答案

假设createdjava.util.Date,则必须在Java中执行DATEDIFF并将该属性与结果日期进行比较:

Supposing that created is a java.util.Date, you have to perform the DATEDIFF in java and compare the property with the resulting date:

Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_YEAR, -20);
Date myDate = c.getTime();

predicates.add(cb.lessThanOrEqualTo(root.<Date>get("created"), myDate));

这篇关于使用JPA标准查询比较两个日期之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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