When using JPA, the new Date() time is inserted into the database and the time difference is 8 hours. Solution
1. Docker deployment environment
Check the time zone of the docker image separately. If the time zone is incorrect, it is recommended to bind the time zone of the docker image to the system time zone.
version: "3"
services:
deploy:
build: doc
container_name: doc_server
network_mode: "host"
ports:
- 8080:8080
volumes:
- ./log:/log
# 时区绑定到系统时间
- /etc/timezone:/etc/timezone
- /etc/localtime:/etc/localtime
2. When JPA adds data
CreateTime adopts the new Date() method, and the time difference may occur. The solution is as follows:
a. Modify serverTimezone=GMT%2b8 of JDBC parameters
datasource:
type: com.zaxxer.hikari.HikariDataSource
url: jdbc:mysql://17.17.27.21:3306/dbname?useUnicode=true&characterEncoding=utf8&useSSL=false&useLegacyDatetimeCode=false&serverTimezone=GMT%2b8
username: root
password: root
b. Modify to add a comment on the time entity class: @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
// 创建时间
@Basic
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@Column(name = "create_time", columnDefinition = "datetime COMMENT '创建时间'")
private Date createTime;
// 更新时间
@Basic
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@Column(name = "update_time", columnDefinition = "datetime COMMENT '更新时间'")
private Date updateTime = new Date();
After adding, redeploy the service and add a new piece of data to check whether it is normal. Good luck!