簡體   English   中英

在JOINED繼承中從父類到子類的Hibernate升級對象

[英]Hibernate upgrade object from parent class to child class in JOINED inheritance

我在我的項目上使用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);

但是,當我進行休眠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實體已經存在。

這個問題有解決方案嗎?

JPA是一種將Java域模型映射到關系數據庫模式的方法。 由於在Java中沒有“將父類提升為子類”之類的東西,因此JPA不支持這種操作。

話雖這么說,你可以使用本機更新查詢可能達到期望的行為。 您將需要更新discriminator列( DTYPE )列,並將新行插入到與該子實體相對應的表中(請注意,在SINGLE_TABLE策略中,更新discriminator列就足夠了)。

恕我直言,更好的解決方案是刪除父實體並插入新的子實體。 如果您擔心參照完整性,則可能應該從繼承切換為composition

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM