【问题标题】:Hibernate upgrade object from parent class to child class in JOINED inheritanceHibernate将对象从父类升级到JOINED继承中的子类
【发布时间】:2018-03-01 17:12:00
【问题描述】:

我在我的项目中使用Spring Data JpaHibernate

我有三张桌子:

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
class Parent {
   String id;
   String name;
}

@Entity
class FirstChild extends Parent {
   ...
}

@Entity
class SecondChild extends Parent {
   ...
}

在我的逻辑的第一步,我应该在没有子类型的情况下保存 Parent object。 第二步,我知道它应该属于哪个Child 表。

例如:

Parent parent = parentRepository.findById("id");

FirstChild firstChild = new FirstChild();
firstChild.setId(parent.getId());
firstChild.setName(parent.getName());

parentRepository.save(firstChild);

但是当我执行 Hibernate save 时,它会抛出异常:

o.h.e.i.DefaultLoadEventListener Load request found matching entity in context, but the matched entity was of an inconsistent return type; returning null

据我了解,它不知道如何将 entity 从父类型升级到子类型,并且由于冲突而引发异常 - 具有相同 id 的实体已经存在。

这个问题有解决办法吗?

【问题讨论】:

    标签: java spring hibernate jpa spring-data-jpa


    【解决方案1】:

    JPA 是一种将 Java 域模型映射到关系数据库模式的方法。由于 Java 中没有“将父类提升为子类”之类的东西,因此 JPA 不支持这种操作。

    话虽如此,您可以可能使用本机更新查询实现所需的行为。您需要更新鉴别器列 (DTYPE) 列,并将新行插入到与子实体对应的表中(请注意,在 SINGLE_TABLE 策略中,更新鉴别器列就足够了)。

    恕我直言,一个更好的解决方案是删除父实体并插入一个新的子实体。如果您担心引用完整性,也许您应该从 inheritance 切换到 composition

    【讨论】:

    • 其实一切都在寻找我的解决方法,但有相同的想法,谢谢。
    猜你喜欢
    • 2014-01-21
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多