[英]Create column type Datetime in Hibernate for LocalDateTime
[英]Create DATETIME in MariaDB using LocalDateTime column type in JPA
我需要使用JPA中的LocalDateTime
列类型在MariaDB中创建DATETIME
列。
我创建了这个实体:
@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());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.