我正在进行一些测试,以将 UTC 定义为我的应用程序的默认时区。首先,我希望我的日期时间值与 UTC 一起存储。
根据 VLAD MIHALCEA ( https://vladmihalcea.com/how-to-store-date-time-and-timestamps-in-utc-time-zone-with-jdbc-and-hibernate/ ) 和 https://moelholm.com/2016/11/09/spring-boot-controlling-timezones-with-hibernate/我已经在我的属性文件中设置了:
spring.jpa.properties.hibernate.jdbc.time_zone= UTC
为了测试我使用的是 h2 数据库,我创建了一个包含所有 java 8 dateTime 类型的示例实体。
在我的 liquibase 配置中,它们是这样定义的:
<column name="instant" type="timestamp"/>
<column name="local_date" type="date"/>
<column name="local_time" type="time"/>
<column name="offset_time" type="time"/>
<column name="local_date_time" type="timestamp"/>
<column name="offset_date_time" type="timestamp"/>
<column name="zoned_date_time" type="timestamp"/>
我认为我对每个字段都使用了良好的类型。它适用于除“local_time”和“offset_time”之外的所有字段,它们是时间 sql 类型而不是时间戳。
如您所见,我在上午 8 点 39 分(巴黎格林威治标准时间+2)添加了这一行,并且时间戳具有良好的 UTC 值(上午 6 点 38 分)。 但是“local_time”和“offset_time”都有一个奇怪的值(早上 7:39)。
我想知道为什么会出现这种行为,如果你们中的一些人知道为什么我的两个时间字段不能正确存储值的话。
附言:版本:
- hibernate :5.2.17.Final
- Spring 启动:2.0.4.RELEASE
我的示例实体用于插入数据:
import javax.persistence.*;
import java.io.Serializable;
import java.time.*;
import java.util.Objects;
@Entity
@Table(name = "avdev_myData")
public class MyData implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;
@Column(name = "name")
private String name;
@Column(name = "instant")
private Instant instant;
@Column(name = "local_date")
private LocalDate localDate;
@Column(name = "local_time")
private LocalTime localTime;
@Column(name = "offset_time")
private OffsetTime offsetTime;
@Column(name = "local_date_time")
private LocalDateTime localDateTime;
@Column(name = "offset_date_time")
private OffsetDateTime offsetDateTime;
@Column(name = "zoned_date_time")
private ZonedDateTime zonedDateTime;
最佳答案
试一试:
@SpringBootApplication
public class YourApplication {
@PostConstruct
void started() {
// set JVM timezone as UTC
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}
}
关于java - hibernate + spring boot store date on UTC time zone 麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52363781/