在MySQL中持久化java LocalDate [英] persist java LocalDate in MySQL

查看:1093
本文介绍了在MySQL中持久化java LocalDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个java客户端应用程序,使用:SE 8,MySQL 5.6(Connector / J 5.1),JPA 2.1。当我尝试持有具有ID(int自动增量),date(LocalDate)的实体时。抛出异常说:

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

MySQL(我的意思是连接器)不支持新的日期和时间API或什么。如果是这样我该怎么办?

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;


推荐答案

注册自定义公司nverter应该可以帮助你解决问题

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

有关转换LocalDate的更多信息 info 以及更多关于使用的信息转换器

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

这篇关于在MySQL中持久化java LocalDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆