[英]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種選擇:
刪除Serializable
接口。 將Serializable
放在所有實體上並不是一個“好習慣”。 只有當您要將它的實例用作分離對象時才需要它: JPA實體何時以及為何應該實現Serializable接口? 。
使用Timestamp類型而不是LocalDateTime。 在我看來它是等價的:
https://github.com/javaee/jpa-spec/issues/63
默認情況下,Instant,LocalDateTime,OffsetDateTime和ZonedDateTime映射為時間戳值。 您可以使用@TeMPOraL標記其中一種類型的屬性,以指定用於持久保存該屬性的不同策略。
@SuppressWarnings("squid:S3437")
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.