JPA AttributeConverter被忽略

Joe*_*nst 0 java hibernate jpa java-8

我正在尝试使用AttributeConverter使用Hibernate 4.3.0将新的Java 8 ZonedDateTime值存储在MySQL数据库(DATETIME字段)中.

当我尝试执行更新时,我收到此错误:

...Data truncation: Incorrect datetime value: '\xAC\xED\x00\x05sr\x00\x0Djava.time.Ser\x95]\x84\xBA\x1B"H\xB2\x0C\x00\x00xpw\x0D\x06\x00\x00\x07\xE0\x02\x11\x0B&\xEE\xE0\x08\x' for column...
Run Code Online (Sandbox Code Playgroud)

我已经阅读了许多SO答案,说使用转换器方法,所以我写了一个:

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.sql.Date;
import java.time.LocalDate;
import java.time.ZonedDateTime;

@Converter(autoApply = true)
public class ZonedDateTimeConverter implements AttributeConverter<ZonedDateTime, Date> {
    @Override
    public Date convertToDatabaseColumn(ZonedDateTime zonedDateTime) {
        if (zonedDateTime == null) return null;

        return java.sql.Date.valueOf(zonedDateTime.toLocalDate());
    }

    @Override
    public ZonedDateTime convertToEntityAttribute(Date date) {
        if (date == null) return null;

        LocalDate localDate = date.toLocalDate();
        return ZonedDateTime.from(localDate);
    }
}
Run Code Online (Sandbox Code Playgroud)

......但它永远不会被召唤.

我甚jpaProperties.put("hibernate.archive.autodetection", "class, hbm");至已添加到我的jpaProperties,但没有运气.ZonedDateTimeConverter类与我的实体位于同一个包中,因此应该扫描它.

我在这里错过了什么?

小智 7

阅读JPA 2.1规范:

"支持所有基本类型的转换,但以下情况除外:Id属性(包括嵌入式ID和派生标识的属性),版本属性,关系属性以及显式注释为枚举或时态的属性或在XML描述符中指定的属性".

您的ZonedDateTime字段是否有可能在您的实体中使用@Id或@Temporal注释?