Avd*_*v4j 5 java spring datetime hibernate spring-boot
我正在做一些测试以将 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
Run Code Online (Sandbox Code Playgroud)
为了测试我使用的是 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"/>
Run Code Online (Sandbox Code Playgroud)
我想我在每个领域都使用了良好的类型。它适用于除“local_time”“offset_time”之外的所有字段,它们是时间 sql 类型而不是时间戳。
如您所见,我在上午 8:39(巴黎 GMT+2)添加了这一行,时间戳具有良好的 UTC 值(上午 6:38)。但是“local_time”和“offset_time”都有一个奇怪的值(7:39am)。
我想知道为什么这种行为,如果你们中的一些人知道为什么我的两个时间字段不能正确存储值。
PS:版本:
我的示例实体用于插入数据:
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;
Run Code Online (Sandbox Code Playgroud)
小智 7
试试:
@SpringBootApplication
public class YourApplication {
@PostConstruct
void started() {
// set JVM timezone as UTC
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}
}
Run Code Online (Sandbox Code Playgroud)
我在休眠错误跟踪器中打开了一个问题并得到了我的问题的答案。
对于 LocalTime,转换是相对于 1970 年 1 月 1 日,而不是我运行测试的那一天。所以 DST 没有被处理。
根据 Vlad Mihalcea 的说法,我们必须使用 LocalDateTime 来代替,因为我们知道日期,当然也知道它是否处于夏令时期间。
问候