【问题标题】:@Converter does not work with JPA 2.4@Converter 不适用于 JPA 2.4
【发布时间】:2016-09-15 16:39:03
【问题描述】:

我无法让 JPA 2.4 中的 @Converter 正常工作。我在herehere 上关注了示例。当我尝试持久化我的实体时,它失败并出现以下异常。有没有人成功地做到这一点?有什么需要注意的吗?

原因:org.apache.openjpa.persistence.PersistenceException:数据截断:不正确的日期时间值:'\xAC\xED\x00\x05sr\x00\x16org.joda.time.DateTime\xB8

转换器类

@Converter
public class DateTimeConverter implements AttributeConverter<DateTime, Timestamp> {
    @Override
    public Timestamp convertToDatabaseColumn(DateTime dateTime) {
        return new Timestamp(dateTime.getMillis());
    }

    @Override
    public DateTime convertToEntityAttribute(Timestamp date) {
        return new DateTime(date);
    }
}

而且用法看起来像

@Column(name = "created_on")
@Convert(converter = CustomConverter.class)
private DateTime createdOn;

【问题讨论】:

    标签: java mysql jpa-2.0 jodatime


    【解决方案1】:

    这里有几个错误的地方:

    1. 您得到的异常表明列中包含的当前值是序列化的 org.joda.time.DateTime。

    2. 字段的类型应该是转换器的convertToEntityAttribute 方法的返回类型,所以在你的情况下DateTime 不是Date

    【讨论】:

    • @ks_ 抱歉。我正在尝试几件事,但我发布的内容不正确。我的实体中的返回类型是 joda.DateTime。我已经在问题中更正了它。
    • 所以重置架构以解决问题 1 应该没问题。
    • 重置架构?我试图在我的一个转换器方法中打断点,我发现我们根本没有进入 Converter 类。我会不会遗漏任何其他接线?
    • 您的数据库中的createdOn 列中有无效数据。很可能您在没有 typeconverter 的情况下启动了 jpa,它创建了一个二进制列并将数据作为序列化对象插入。删除列并让 jpa 重新创建它,或者删除整个数据库以重置架构。
    • 这听起来不对。如果我没有点击进行实际转换的代码,那几乎不可能是架构问题。问题是数据应用程序正在尝试推送,而不是当 DB 持久化它时。无论如何,我启动了我的服务器,让 JPA 来完成它的工作,然后重新创建了模式。同样的错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-03
    • 2012-04-14
    相关资源
    最近更新 更多