【发布时间】:2019-04-29 04:22:26
【问题描述】:
数据库函数date_trunc('day', (entity.date AT TIME ZONE 'UTC')) 的 JPQL/JPA/Hibernate 等价物是什么?
我需要在 Spring Boot 应用程序中四舍五入到全天(和几周等),Hibernate 在 Postgresql 数据库之上运行。这个查询在本机 postgresql 中是可能的,但我还没有弄清楚如何在 Hibernate 中执行它。时区(如“UTC”、“Europe/Amsterdam”)和日期部分(如“日”、“年”)可能会有所不同,因此我不能将其设置为默认值。
我在 Hibernate 论坛上发现了一篇古老的帖子,没有任何回复:https://forum.hibernate.org/viewtopic.php?f=1&t=990451
我还发现了一个相关的 StackOverflow 问题,发帖人直接想选择某个日期作为某个时区。但它没有回复:HQL equivalent of Postgres' "datetime at time zone"
我的整个查询(没有 where)看起来像这样,所以用不同的方法来实现这一点也可以。
"SELECT NEW " + AggregateQueryEntity.class.getName() +
"(date_trunc('" + aggregationPeriod.toString() +
"', a.date), a.alertConfiguration.id.id, a.alertConfiguration.name, a.alertLevel, count(*)) from Alert a" +
whereClause.toString() +
" GROUP BY 1, a.alertConfiguration.id.id, a.alertConfiguration.name, a.alertLevel" + //column 1 is the truncated date
" ORDER BY 1, alertLevel DESC"
编辑:cmets on answer。
弗拉德的回答很棒,我对其进行了更多调整,以便将日期部分也作为变量。此外,我必须覆盖标准的 Hibernate 行为,它将Date 列生成为timestamp without timezone,并通过将其放在我的列定义中明确地使它们成为timestamp with timezone:
@Column(columnDefinition = "TIMESTAMP WITH TIME ZONE") private Date date;
更多阅读请见https://wiki.postgresql.org/wiki/Don%27t_Do_This#Don.27t_use_timestamp_.28without_time_zone.29
根据 Vlad 的另一篇博文 https://vladmihalcea.com/how-to-store-date-time-and-timestamps-in-utc-time-zone-with-jdbc-and-hibernate/,使用 Hibernate 属性 hibernate.jdbc.time_zone 并以 UTC 启动 JVM 也是一个好主意。为了解决我所有的时区问题,我也必须这样做。
【问题讨论】:
标签: java spring hibernate jpa jpql