在spring数据jpa/hibernate(hql)查询中返回带有特定时区的当前时间戳值?

wj8zmpe1  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(438)

我有一个springbootapi,它使用springdatajpa(1.5.9)/hibernate(5.0.12)来查询作为rds托管在aws上的postgresql数据库。它被设置为中心时间(cst),我有一些hql(hibernate)查询使用 CURRENT_TIMESTAMP 函数,但不幸的是,奇怪的是,每当hql查询使用 CURRENT_TIMESTAMP 快跑。
我需要一个简单的方法 CURRENT_TIMESTAMP 在hql查询中为中心时间(cst)。我试着用纯sql查询数据库,类似的方法奏效了:

CURRENT_TIMESTAMP at TIME ZONE 'America/Chicago'

不幸的是,我似乎无法在hql中使用它,因为intellij/hibernate抛出了一个编译错误:

<expression> GROUP, HAVING, or ORDER expected, got 'AT'

我使用的hql查询示例是:

@Query(value = "SELECT customerCoupons FROM CustomerCouponsEntity customerCoupons " 
+ "WHERE customerCoupons.couponCode = :couponCode "
+ "AND customerCoupons.expiredDate >= CURRENT_TIMESTAMP "
+ "AND customerCoupons.startDate <= CURRENT TIMESTAMP "
)

List<CustomerCouponsEntity> findByCouponCode(@Param("couponCode") String couponCode);

任何帮助都将不胜感激。我在aws中将db设置为cst,所以我甚至没想到会出现这种情况 CURRENT_TIMESTAMP 返回utc值(对我来说仍然没有意义,除非它以某种方式使用jdbc驱动程序时区或jvm?我的意思是,这是一个hibernate查询,所以它不是纯sql,对吗?)

ivqmmu1c

ivqmmu1c1#

您应该尝试在spring引导属性文件中设置hibernate时区。例子:

spring.jpa.properties.hibernate.jdbc.time_zone=YOUR_TIMEZONE

确保\u时区的值与db时区匹配。
我想这篇文章会有帮助的

ny6fqffe

ny6fqffe2#

张贴我自己的答案;
根据本文,我尝试在properties/yaml中设置时区:https://moelholm.com/blog/2016/11/09/spring-boot-controlling-timezones-with-hibernate
但不管我怎么做都没有用。我确定我是在hibernate5.2.3或更高版本,它不会工作。
我还尝试在hql查询中添加“at timezone”,但代码无法编译。我猜即使这是有效的sql,它也不能与hibernatesql查询一起工作。

CURRENT_TIMESTAMP at TIME ZONE 'America/Chicago'

不管怎样,唯一有效的办法是:

@PostConstruct
  void started() {
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
  }

相关问题