java.time和JPA

问题描述 投票:6回答:2

来自LocalDateTime包的java.time类是value based classes。如果我有一个实体使用这样的对象作为字段,我会遇到以下“问题”:不应序列化基于值的类。但是,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..
}
java jpa java-8 sonarqube java.time.instant
2个回答
2
投票

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

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

  1. 删除Serializable界面。将Serializable放在所有实体上并不是一个“好的做法”。仅当您要将其实例用作分离对象时才需要它:When and why JPA entities should implement Serializable interface?
  2. 使用Timestamp类型而不是LocalDateTime。在我看来它是等价的:

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

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

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

1
投票

我不太明白你的数据库从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接受)并返回。

© www.soinside.com 2019 - 2024. All rights reserved.