繁体   English   中英

本地日期时间 JPA - Java 8

[英]LocalDateTime JPA - Java 8

当我的字段被 JPA 保存时,在某些时候它会以正确的日期广告时间保存,而其他时间则不会保存,只有日期是正确的,但时间为零(00:00:00)。

更正时间: 13/11/2019 11:05:12
不正确: 13/11/2019 00:00:00

我的数据库是 postgresql 并且我的字段是timestamp类型

在 java class,我的字段注释如下:

@Column(name = "DAT_ACTION")
private LocalDateTime espDatAction;

我现在不知道发生了什么,因为应用程序的操作是相同的并且具有不同的行为

If you want to store a LocalDate attribute in a DATE column or a LocalDateTime in a TIMESTAMP column, you need to define the mapping to java.sql.Date or java.sql.Timestamp yourself. 您可以尝试添加如下内容并重新启动应用程序,它应该在它之后正确保存:

import java.time.LocalDateTime;
import java.sql.Timestamp;
 
@Converter(autoApply = true)
public class LocalDateTimeAttributeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
     
    @Override
    public Timestamp convertToDatabaseColumn(LocalDateTime locDateTime) {
        return locDateTime == null ? null : Timestamp.valueOf(locDateTime);
    }
 
    @Override
    public LocalDateTime convertToEntityAttribute(Timestamp sqlTimestamp) {
        return sqlTimestamp == null ? null : sqlTimestamp.toLocalDateTime();
    }
}

这种方式配合JPA 2.2新版使用

import com.fasterxml.jackson.annotation.JsonFormat;

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern="dd/MM/yyyy HH:mm:ss")
private LocalDateTime espDatAction;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM