0

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?

Peter Penzov
  • 1,126
  • 134
  • 430
  • 808
  • Are you sure you used LocalDateTime in your try without @Temporal because LocalDateTime should be DATETIME in the db. When I tried it with spring-boot-starter-parent, it worked. – Tom Oct 08 '18 at 10:02
  • It turns out that DATETIME was created - I was wrong. – Peter Penzov Oct 08 '18 at 10:41

1 Answers1

4

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());
    }
}
user987339
  • 10,519
  • 8
  • 40
  • 45