如何在Spring JPA中将UTC格式的时间戳记保存为Audit字段@ CreatedDate,@ LastModifiedDate [英] How to save timestamp in UTC format for Audit fields @CreatedDate, @LastModifiedDate in Spring JPA

查看:76
本文介绍了如何在Spring JPA中将UTC格式的时间戳记保存为Audit字段@ CreatedDate,@ LastModifiedDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的带有审核字段的实体基类.对于@ CreatedDate,@ LastModifiedDate字段,默认情况下节省了我的系统时间.我的要求是在UTC中保存时间戳.

This is my Base Class for Entities with audit fields. For fields @CreatedDate, @LastModifiedDate, by default it is saving my system time. My requirement is to save timestamp in UTC.

有人对此有解决方案吗?

Does anyone have a solution of this?

import java.time.LocalDateTime;

import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;

import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import lombok.Data;


@MappedSuperclass
@Data
@EntityListeners(AuditingEntityListener.class)
public abstract class BaseEntity {

    @LastModifiedDate
    @Column(name="last_modified_datetime")
    private LocalDateTime lastModifiedDateTime;

    @CreatedDate
    @Column(name="created_datetime")
    private LocalDateTime createdDateTime;

}

推荐答案

这是时区问题.将此代码用于Spring Boot.

This is problem of time zone. use this code for spring boot.

@PostConstruct
public void setTimeZone() {
   TimeZone.setDefault(TimeZone.getTimeZone("Etc/UTC"));
}

这篇关于如何在Spring JPA中将UTC格式的时间戳记保存为Audit字段@ CreatedDate,@ LastModifiedDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆