LocalDateTimeをDBに保存できない

問題

LocalDateTime.now()を引数としてDBに保存しようとすると下記のエラーが吐かれる。

ERROR [2017-05-24 01:46:42,641] io.dropwizard.jersey.errors.LoggingExceptionMapper: Error handling a request: a16f2a5e900f29b6
! com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '\xAC\xED\x00\x05sr\x00\x0Djava.time.Ser\x95]\x84\xBA\x1B"H\xB2\x0C\x00\x00xpw\x0E\x05\x00\x00\x07\xE1\x05\x18\x0A.*$\xC6\xAC@x' for column 'date' at row 1
! at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3968)
! at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3906)
! at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2524)
! at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2677)
! at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2549)
! at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1861)
! at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2073)
! at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2009)
! at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5098)
! at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1994)
! at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)



解決

LocalDateTimeTimestampの変換ができるように、変換クラスを作成する。

LocalDateTimeConverter.java

package com.midcareer.midcommon.util;

import java.sql.Timestamp;
import java.time.LocalDateTime;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime,  Timestamp> {
    @Override
    public Timestamp convertToDatabaseColumn(LocalDateTime localDateTime) {
        return (localDateTime == null ? null : Timestamp.valueOf(localDateTime));
    }

    @Override
    public LocalDateTime convertToEntityAttribute(Timestamp  timestamp) {
        return (timestamp == null ? null : timestamp.toLocalDateTime());
    }
}


Tableクラスの型がLocalDateTimeのプロパティに@Convert(converter = LocalDateTimeConverter.class)を付け足す。

@Column(name="date")
@Convert(converter = LocalDateTimeConverter.class)
private LocalDateTime date;

無事DBに日時のデータを保存できるようになった。よかった。