Java 使用 JPA Criteria Query 比较两个日期之间的差异

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24669544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 13:58:13  来源:igfitidea点击:

Compare difference between two dates using JPA Criteria Query

javajpacriteria-apidatediff

提问by Ashvin Kanani

I am using MySQL as a backend for my application.

我使用 MySQL 作为我的应用程序的后端。

I want to execute query below using JPA Criteria Query.

我想使用 JPA Criteria Query 在下面执行查询。

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

Note: Type of createdis TIMESTAMP

注意:类型createdTIMESTAMP

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

Can any one help?

任何人都可以帮忙吗?

Thanks in advance.

提前致谢。

采纳答案by perissf

Supposing that createdis a java.util.Date, you have to perform the DATEDIFFin java and compare the property with the resulting date:

假设这created是 a java.util.Date,您必须DATEDIFF在 java 中执行并将该属性与结果日期进行比较:

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

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