使用JPA时new Date()时间插入数据库时间差8个小时解决方法

使用JPA时new Date()时间插入数据库时间差8个小时解决方法

一. Docker部署环境时

分别检查docker内部镜像时区,如果时区不正确,推荐将docker镜像的时区和系统时区绑定。

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

二. JPA进行新增数据时

createTime采用new Date()方式,则有可能出现时差问题,解决方案如下:

a. 修改JDBC参数的 serverTimezone=GMT%2b8

     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. 修改在时间的实体类上加注解: @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();

添加后,重新部署服务,新增一条数据查看是否正常,祝君好运!

猜你喜欢

转载自blog.csdn.net/doinbb/article/details/105141155