在JOINED继承中从父类到子类的Hibernate升级对象 [英] Hibernate upgrade object from parent class to child class in JOINED inheritance

查看:87
本文介绍了在JOINED继承中从父类到子类的Hibernate升级对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中使用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表.

On the first step of my logic I should save Parent object without child type. And on the second step I know to which Child table it should belong.

例如:

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

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

parentRepository.save(firstChild);

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

But when I do a Hibernate save it throws me exception:

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的实体已经存在.

As I understand it doesn't know how to upgrade entity from parent to child type and just throws an exception because of conflict - entity with same id is already there.

这个问题有解决方案吗?

Is there any solutions for this problem?

推荐答案

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

JPA is a means of mapping your Java domain model onto a relational database schema. Since there is no such thing as 'promoting a parent class to a child class' in Java, there is no support in JPA for such an operation.

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

That being said, you could probably achieve the desired behavior using a native update query. You would need to update the discriminator column (DTYPE) column, and insert a new row into the table corresponding to the child entity (note that in the SINGLE_TABLE strategy, updating the discriminator column would suffice).

IMHO更好的解决方案是删除父实体并插入新的子实体.如果您担心参照完整性,则应该从继承转换为组成.

A much better solution IMHO, is to delete the parent entity and insert a new child entity. If you're concerned about referential integrity, perhaps you should switch from inheritance to composition.

这篇关于在JOINED继承中从父类到子类的Hibernate升级对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆