繁体   English   中英

java.time和JPA

[英]java.time and JPA

来自包java.time LocalDateTime类是基于值的类 如果我有一个实体使用这样的对象作为字段,我会遇到以下“问题”:不应序列化基于值的类。 但是,JPA实体必须实现Serializable接口。 这个悖论的解决方案是什么? 不应该有人使用LocalDateTime作为JPA实体的字段吗? 使用日期代替? 这将是不满意的。

这个问题是一个声纳规则squid:S3437 ,因此项目中有很多错误,因为我们从Date更改为LocalDateTime ...

基于价值的课程使用导致的不合规解决方案:

@Entity
public class MyEntity implements Serializable{
    @Column
    private String id; // This is fine
    @Column
    private LocalDateTime updated; // This is not ok, as LocalDateTime is a value based class
    @Column
    private Date created; // This however is fine..
}

我不太明白你的数据库从jpa接受了什么。 当我处理Postgres时,我使用自定义转换器:

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.sql.Timestamp;
import java.time.LocalDateTime;

@Converter(autoApply = true)
public class LocalDateTimePersistenceConverter 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());
    }
}

我用这种方式使用它:

@Column(name = "create_date")
@Convert(converter = LocalDateTimePersistenceConverter.class)
private LocalDateTime createDate;

你看,在这里我将LocalDateTime转换为Timestamp(由postgres接受)并返回。

我的回答看起来很直接,毫无价值,但更多的是将事情放在一起并总结。

首先,它没有这个问题的“金子弹”解决方案。 肯定要改变一些东西,我看到3种选择或3种选择:

  1. 删除Serializable接口。 Serializable放在所有实体上并不是一个“好习惯”。 只有当您要将它的实例用作分离对象时才需要它: JPA实体何时以及为何应该实现Serializable接口?

  2. 使用Timestamp类型而不是LocalDateTime。 在我看来它是等价的:

https://github.com/javaee/jpa-spec/issues/63

默认情况下,Instant,LocalDateTime,OffsetDateTime和ZonedDateTime映射为时间戳值。 您可以使用@TeMPOraL标记其中一种类型的属性,以指定用于持久保存该属性的不同策略。

  1. 如果两个第一选项都不适合你,那么(我很确定,你知道该怎么做) - 抑制这个警告@SuppressWarnings("squid:S3437")

暂无
暂无

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

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