简体   繁体   English

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

[英]Create DATETIME in MariaDB using LocalDateTime column type in JPA

I need create DATETIME column in MariaDB using LocalDateTime column type in JPA. 我需要使用JPA中的LocalDateTime列类型在MariaDB中创建DATETIME列。

I created this entity: 我创建了这个实体:

@Column
private LocalDateTime created_at;

but when I depot the code the column in MariDB is updated to DATE . 但是当我存放代码时,MariDB中的列将更新为DATE I need DATETIME . 我需要DATETIME

I also tried this: 我也试过这个:

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

But when I deploy the code I get error: 但是,当我部署代码时,我得到了错误:

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

I use Java 10 and spring-boot-starter-parent 我使用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>

Is there any solution to this problem? 有什么解决办法吗? For example is there a way to set the column type into the entity as DATETIME without using @Temporal ? 例如,有没有一种方法可以在不使用@Temporal情况下将列类型设置为DATETIME

If you want to store a LocalDateTime in a TIMESTAMP column, you need to implement the mapping to java.sql.Timestamp . 如果要将LocalDateTime存储在TIMESTAMP列中,则需要实现到java.sql.Timestamp的映射。

You need to implement the AttributeConverter interface. 您需要实现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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM