java - JPA AttributeConverter 被忽略

标签 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...

我读过很多答案说要使用转换器方法,所以我写了一个:

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/

相关文章:

java - 如何在java控制台(没有UI)中显示下载文件的百分比进度?

java - 在这个涉及数据分页的 Java 方法中可以对什么进行单元测试?

JavaFX StackPane 边界未更新

hibernate - java.lang.NoSuchMethodError : javax/persistence/spi/PersistenceUnitInfo. getValidationMode()Ljavax/persistence/ValidationMode

java - Hibernate DefaultEntityAliases 引发 NullPointerException

java - 在双向持久化子实体时如何级联父实体

java - JPA 2.0 中的 session 和事务有什么区别?

java - JPA - 跨 EntityManager 获取更新/同步的实体(刷新)

java - 如何将jar包集成到maven项目中

java - JUnit - 使用可重用函数进行测试;有效性