首页 文章

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

提问于
浏览
0

我需要在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>

有没有解决这个问题的方法?例如,是否有一种方法可以将列类型设置为实体 DATETIME 而不使用 @Temporal

1 回答

  • 2

    如果要在 TIMESTAMP 列中存储 LocalDateTime ,则需要实现到 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());
        }
    }
    

相关问题