在 MariaDB 中使用 JPA 中的 LocalDateTime 列类型创建 DATETIME



我需要在 MariaDB 中使用 JPA 中的列类型创建DATETIMELocalDateTime

我创建了这个实体:

@Column
private LocalDateTime created_at;

但是当我解码代码时,MariDB 中的列会更新为DATE.我需要DATETIME.

我也试过这个:

@Column
@Temporal(TemporalType.TIMESTAMP)
private LocalDateTime created_at;

但是当我部署代码时,我收到错误:

@Temporal should only be set on a java.util.Date or java.util.Calendar property

我使用 Java 10 和spring-boot-starter-parent

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath />
</parent>

这个问题有什么解决方案吗?例如,有没有办法在不使用@Temporal的情况下将列类型设置为DATETIME实体?

如果要将LocalDateTime存储在TIMESTAMP列中,则需要实现映射到java.sql.Timestamp

您需要实现 AttributeConverter 接口。

@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());
}
}

相关内容

最新更新