java localdate mysql,在MySQL中持久化java LocalDate

本文探讨了在Java应用中使用JPA 2.1和MySQL 5.6时遇到的日期类型不兼容问题,介绍了如何通过注册LocalDatePersistenceConverter解决`MysqlDataTruncation`异常,重点讲解了如何将LocalDate转换为数据库所需的java.sql.Date格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;

解决方案

Registering the custom converter should help you solve your issue

@Converter(autoApply = true)

public class LocalDatePersistenceConverter implements

AttributeConverter {

@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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值