java - 在 HQL 中查找日期之间的实体
问题描述
我正在使用 HQL 和javax.persistence
. 在我的 MySQL 数据库中,我有一个日期时间(例如2018-01-22 18:00:00
)。从客户端,我被传递了一个没有时间的日期(例如2018-01-20
)。我想找到日期时间在 astartDate
和a 之间的所有实体endDate
。
public List<BillingRunEntity> getBillingRuns(List<String> accountIds, LocalDate startDate, LocalDate endDate) {
String query = "SELECT DISTINCT bre " +
"FROM BillingRunEntity bre " +
"WHERE bre.accountId in :accountIds " +
"AND bre.billingDateTime BETWEEN :startDate AND :endDate";
return entityManager
.createQuery(query, BillingRunEntity.class)
.setParameter("accountIds", accountIds)
.setParameter("startDate", startDate)
.setParameter("endDate", endDate)
.getResultList();
}
而我BillingRunEntity.java
的billingDateTime
领域:
@Column(name = "billing_date_time")
private ZonedDateTime billingDateTime;
1)尝试运行此查询会导致以下错误。考虑到我不在乎时间,我该如何解决这个问题?
java.lang.IllegalArgumentException: Parameter value [2018-07-03] did not match expected type [java.time.ZonedDateTime (n/a)]
at org.hibernate.jpa.spi.BaseQueryImpl.validateBinding(BaseQueryImpl.java:874)
at org.hibernate.jpa.internal.QueryImpl.access$000(QueryImpl.java:80)
at org.hibernate.jpa.internal.QueryImpl$ParameterRegistrationImpl.bindValue(QueryImpl.java:248)
at org.hibernate.jpa.spi.BaseQueryImpl.setParameter(BaseQueryImpl.java:620)
at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:180)
at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:49)
2)这个查询会按我期望的方式工作吗?我不关心这里的时间 - 如果数据库有2018-01-22 18:00:00
,并且我通过了startDate
一个(或什至)2018-01-22
的结束日期,我希望提取该记录。2018-01-23
2018-01-22
解决方案
假设您ZonedDateTime
在数据库中始终存储在 UTC 中,您可以简单地转换为LocalDate
ZoneId utc = ZoneId.of("UTC");
ZonedDateTime startTime = startDate.atStartOfDay(utc);
ZonedDateTime endTime = endDate.atStartOfDay(utc).plusDays(1).minusNanos(1);
[...]
.setParameter("startDate", startTime)
.setParameter("endDate", endTime)
minusNanos(1)
可能是矫枉过正,但BETWEEN
运营商在两端都具有包容性。
如果您没有对数据库中的所有值使用相同的时区,您可能必须深入研究billing_date_time
表使用的列类型以了解它如何处理时区信息。
推荐阅读
- angularjs - 在角度 7 中读取没有 HttpClient 的文本文件或 xml
- c# - Possibility to load video without extension from StreamingAssets?
- python - 如何按月和年将熊猫数据框划分为多个数据框
- plugins - 从 CRM 沙盒插件 OnPremise 调用外部 WCF 服务(使用生成的客户端)失败
- python - 什么是在正无穷范围内的非线性激活函数的例子?
- swift - 自包含通用
- pyspark - 使用 pyspark 从数据块中删除红移表
- django - 如何提高多个查询集 django 中的分页性能?
- laravel - 调用 role::create 和 permission::create 时捕获异常
- r - R中Wilcoxon秩和检验中的警告