簡體   English   中英

在MySQL中持久化java LocalDate

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

有關轉換LocalDate 信息的更多信息以及有關使用轉換器的更多信息

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

}

如果使用hibernate,我剛剛在這里找到一個可以利用Java 8支持,該文件位於一個名為hibernate-java8.jar的獨立jar文件中。 所以基本上你可以在你的pom中添加這樣的東西並准備好去:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-java8</artifactId>
</dependency>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM