persist java LocalDate in MySQL

usertest picture usertest · Mar 6, 2015 · Viewed 11.7k times · Source

I'm writing a java client application using: SE 8, MySQL 5.6 (Connector/J 5.1), JPA 2.1. when I try to persist an entity with an ID (int Auto-increment), date (LocalDate). it throw an Exception says:

Internal Exception: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect date value: '\xAC\xED\x00\x05sr\x00\x0Djava.time.Ser\x95]\x84\xBA\x1B"H\xB2\x0C\x00\x00xpw\x07\x03\x00\x00\x07\xDF\x03\x06x' for column 'date' at row 1

does MySQL (I mean The Connector) do not support the new Date and Time API or What. if so What Can I do??

@Entity
@Table(schema="app")
public class Run implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;                     //number of connections

    private LocalDate date;

Answer

Master Slave picture Master Slave · Mar 6, 2015

Registering the custom converter should help you solve your issue

@Converter(autoApply = true)
public class LocalDatePersistenceConverter implements
    AttributeConverter<LocalDate, Date> {
    @Override
    public java.sql.Date convertToDatabaseColumn(LocalDate entityValue) {
        return java.sql.Date.valueOf(entityValue);
    }

    @Override
    public LocalDate convertToEntityAttribute(java.sql.Date databaseValue) {
        return databaseValue.toLocalDate();
    }
}

more about converting the LocalDate info and some more about using the converters