我正在尝试使用 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...
我读过很多答案说要使用转换器方法,所以我写了一个:
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);
}
}
...但它永远不会被调用。
我什至将 jpaProperties.put("hibernate.archive.autodetection", "class, hbm");
添加到我的 jpaProperties 中,但没有运气。 ZonedDateTimeConverter 类与我的实体位于同一包中,因此应该对其进行扫描。
我在这里缺少什么?
最佳答案
阅读 JPA 2.1 规范:
“支持所有基本类型的转换,但以下除外:Id属性(包括 嵌入 ID 和派生身份的属性)、版本属性、关系属性和 属性明确注释为枚举或临时或在 XML 描述符中指定为此类。”
您的 ZonedDateTime 字段是否有可能在实体中用 @Id 或 @Temporal 进行注释?
关于java - JPA AttributeConverter 被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35466433/