正在忽略java JPA AttributeConverter
我正在尝试使用Hibernate 4.3.0使用AttributeConverter将新的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);
}
}
。。。但它从未被呼叫过
我甚至在我的JPA属性中添加了jpaProperties.put("hibernate.archive.autodetection", "class, hbm");
,但没有运气。ZonedDateTimeConverter类与我的实体在同一个包中,因此应该对其进行扫描
我错过了什么
# 1 楼答案
阅读JPA 2.1规范:
“除以下内容外,支持所有基本类型的转换:Id属性(包括 嵌入ID和派生标识的属性)、版本属性、关系属性和 在XML描述符中显式注释为枚举或时态或指定为枚举或时态的属性。"
您的ZonedDateTime字段是否有可能在您的实体中被注释为@Id或@Temporal
# 2 楼答案
好吧,这是我的错。我的应用程序有一部分由Hibernate管理,但有一部分不是。我遇到问题的对象不是由Hibernate管理的,所以不调用JPA是有道理的