【问题标题】:ZonedDateTime to MySQL DateTimeZonedDateTime 到 MySQL 日期时间
【发布时间】:2019-01-13 15:46:03
【问题描述】:

我的应用程序使用 Database-per-tenant 多租户,每个租户都有一个时区。

我不想使用 Timestamp,因为我不想让数据库处理时区转换,但我想做的是在 ZonedDateTime 和 MySQL DateTime 之间进行转换。

在我的应用程序中,我像这样检索租户的当前时间:

ZonedDateTime.of(LocalDateTime.now(), tenant.getTenantZoneId());

我想将其写入数据库,因为分区日期时间会显示它(即应用时区和 DST)。

从数据库中读取时,不需要进行这种转换,我可以假设所有日期时间的时区。

如何进行初始翻译?以及如何以一种很好的方式作为 JPA 提供程序(尤其是休眠)来做到这一点

【问题讨论】:

    标签: mysql datetime java-8 timezone zoneddatetime


    【解决方案1】:

    如果我没听错的话,您想将ZonedDateTime 写入MySQL 的DATETIME 类型,但不保留区域ID 等。如果是这样,您只需将其写入LocalDateTime

    如果您的驱动程序足够新,只需使用PreparedStatement.setObjectLocalDateTime 写入数据库即可:

    preparedStatement.setObject(index, zonedDateTime.toLocalDateTime());
    

    至于阅读,ResultSet.getObject 应该可以:

    LocalDateTime localDateTime = resultSet.getObject(index, LocalDateTime.class);
    ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, tenant.getTenantZoneId());
    

    【讨论】:

    • 这真是太好了!我应该在问题中提到我正在使用 Hibernate JPA,但我认为它可以处理 localdatetime 类型。我会检查,更新我的问题,如果可以接受!
    • 要链接这个答案here,因为它解释了localdatetime与hibernate 5一起使用。
    猜你喜欢
    • 2023-03-09
    • 2019-08-05
    • 1970-01-01
    • 2015-09-03
    • 2011-04-15
    • 2011-08-25
    • 1970-01-01
    • 2015-01-14
    • 2017-12-16
    相关资源
    最近更新 更多