【发布时间】:2021-07-26 02:16:25
【问题描述】:
设置:Spring Boot '2.4.1' 应用程序,(休眠 5.4.25),Java 11
问题如何使用 java.time* 保存日期(德国时间)以便 runtime = db
问题:
在调试期间: ZonedDateTime = 2021-05-03 16:11:42.021236
在数据库中: 日期时间(6) 2021-05-03 14:11:42.021236
@Entity
public class User {
private ZonedDateTime createdAt;
//getter&setter
//calling the setter like like:
user.setCreatedAt(ZonedDateTime.now(ZoneId.of("Europe/Berlin")))
//saving via JPARepo...
Repository.save(user);
application.properties:
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect
#tried but no effect
hibernate.jdbc.time_zone=CET
#tried but no effect
hibernate.jdbc.time_zone=UTC
分级
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-validation'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'mysql:mysql-connector-java'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
【问题讨论】:
-
MySQL中的数据类型是什么?
timestamp?datetime?据我所知,MySQL 无法从ZonedDateTime保存时区,那么您希望它如何工作?另外,当您再次检索该值时,您希望返回哪个ZonedDateTime? -
1) Datetime(6) 2) 我不知道 ZoneDateTime 是否是正确的类。我只想根据德国时间线保存一个日期,例如:Year-Month-Day HH:MM:SS:xxxxxx 2021-05-03 16:11:42.021236 并将其恢复为已保存
-
A
LocalDateTime应该适用于在 MySQL 中保存到datetime和从datetime中检索。然而,JavaLocalDateTime和 MySQLdatetime都没有定义时间点,因为它们不保存时区或 UTC 偏移量。推荐的方法是存储到 MySQL 中的timestamp,然后使用 Basil Bourque 的答案。 MySQL 中的timestamp始终采用 UTC(与您所说的相反)。 -
感谢您提供这些指导性问题和答案 :)
-
您能否详细说明什么是“时间点”,什么不是?
标签: spring-boot hibernate spring-data-jpa java-time zoneddatetime