如何配置 JPA/Hibernate 以将数据库中的日期/时间存储为 UTC (GMT) 时区?考虑这个带注释的 JPA 实体:
public class Event {
@Id
public int id;
@Temporal(TemporalType.TIMESTAMP)
public java.util.Date date;
}
如果日期是 2008 年 2 月 3 日上午 9:30 太平洋标准时间 (PST),那么我希望将 2008 年 2 月 3 日下午 5:30 的 UTC 时间存储在数据库中。同样,当从数据库中检索日期时,我希望将其解释为 UTC。所以在这种情况下,530pm 是 530pm UTC。当它显示时,它将被格式化为太平洋标准时间上午 9:30。
最佳答案
从 Hibernate 5.2 开始,您现在可以通过将以下配置属性添加到 properties.xml
JPA 配置文件中来强制使用 UTC 时区:
<property name="hibernate.jdbc.time_zone" value="UTC"/>
如果您使用的是 Spring Boot,则将此属性添加到您的 application.properties
文件中:
spring.jpa.properties.hibernate.jdbc.time_zone=UTC
关于java - 如何使用 JPA 和 Hibernate 在 UTC 时区中存储日期/时间和时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/508019/