我需要在 MariaDB 中使用 JPA 中的列类型创建DATETIME
列LocalDateTime
。
我创建了这个实体:
@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());
}
}