我需要计算 JPA 中两个日期之间的天数。
例如:
CriteriaBuilder.construct(
MyCustomBean.class
myBean.get(MyBean_.beginDate), //Expression<Date>
myBean.get(MyBean_.endDate), //Expression<Date>
myDiffExpr(myBean) //How to write this expression from the 2 Expression<Date>?
);
到目前为止,我尝试过:
CriteriaBuilder.diff()
。但它不会编译,因为此方法需要一些N extends Number
并且Date
不会扩展Number
。我尝试扩展
PostgreSQL82Dialect
(因为我的目标数据库是 PostgreSQL):public class MyDialect extends PostgreSQL82Dialect { public MyDialect() { super(); registerFunction("datediff", //In PostgreSQL, date2 - date1 returns the number of days between them. new SQLFunctionTemplate(StandardBasicTypes.LONG, " (?2 - ?1) ")); } }
编译成功,请求成功,但返回结果不一致(今天和明天之间的 78 天)。
你会怎么做?
最佳答案
看起来您正在寻找一个使用 JPQL 的解决方案来执行类似 SELECT p FROM Period p WHERE datediff(p.to, p.from) > 10
的查询。
恐怕 JPQL 中没有这样的功能,所以我建议使用 native SQL。如果使用 Hibernate 的 SQLFunctionTemplate
扩展 Dialect,您的想法非常聪明。我宁愿将其更改为使用 DATE_PART('day', end - start)
因为这是使用 PostgreSQL 实现日期之间天数差异的方法。
您还可以定义函数 in PostgreSQL and using it with criteria function()
.
'CREATE OR REPLACE FUNCTION "datediff"(TIMESTAMP,TIMESTAMP) RETURNS integer AS \'DATE_PART('day', $1 - $2);\' LANGUAGE sql;'
cb.function("datediff", Integer.class, end, start);
关于java - 计算JPA中2个日期之间的天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24991581/