![](/img/trans.png)
[英]How to persist Java8 LocalDate / LocalDateTime with ORM Lite?
[英]persist java LocalDate in MySQL
我正在編寫一個java客戶端應用程序,使用:SE 8,MySQL 5.6(Connector / J 5.1),JPA 2.1。 當我嘗試持有具有ID(int自動增量),date(LocalDate)的實體時。 拋出異常說:
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或什么。 如果是這樣我該怎么辦?
@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;
注冊自定義轉換器應該可以幫助您解決問題
@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();
}
}
AttributeConverter也是通用的:
@Converter(autoApply = true)
public class LocalDatePersistenceConverter implements
AttributeConverter<LocalDate, Date> {
@Override
public Date convertToDatabaseColumn(LocalDate entityValue) {
return java.sql.Date.valueOf(entityValue);
}
@Override
public LocalDate convertToEntityAttribute(Date databaseValue) {
return databaseValue.toLocalDate();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.