Search code examples
javahibernatejpaspring-boot-starter

Create DATETIME in MariaDB using LocalDateTime column type in JPA


I need create DATETIME column in MariaDB using LocalDateTime column type in JPA.

I created this entity:

@Column
private LocalDateTime created_at;

but when I depot the code the column in MariDB is updated to DATE. I need 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

    <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?


Solution

  • If you want to store a LocalDateTime in a TIMESTAMP column, you need to implement the mapping to java.sql.Timestamp.

    You need to implement the AttributeConverter interface.

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