gpt4 book ai didi

java - 在 Hibernate 中映射复杂值对象

转载 作者:行者123 更新时间:2023-11-30 06:51:12 25 4
gpt4 key购买 nike

我已经在 Hibernate's forum 上问过这个问题,但我想我也应该在这里问。

我正在尝试映射以下模型,同时保留 TranslatedText 的值语义和Translation值对象:

enter image description here

两个值都是依赖对象

理想情况下我会映射TranslatedText作为<component> Question内和Translation作为<bag><composite-element> TranslatedText内.

如果 Question 的话,映射起来会很简单仅引用一个 TranslatedText ,但由于它引用了两个,我需要某种基于持有值的属性名称的鉴别器( titledescription ),以便映射 Translation带有由 (question_id,property_name,language_code) 组成的外键.

其中一个问题是 propertyName不是模型的一部分,也不应该,但我还没有找到一种方法来强制 Hibernate 插入一个不是来自模型的值。

因此,我尝试改变模型,引入专门的TitleDescription类,这样我就有了 type在那里我可以用作鉴别器。

enter image description here

最后并没有多大帮助:

  <component name="title" class="TranslatedText">

<bag name="translations" table="Translation">
<key>
<!-- PROBLEM: Could not find a way to create a custom join expression on question.id and question.title.type in here. -->
</key>

<composite-element class="Translation">
<!-- PROBLEM: Could not found a way to make Hibernate insert title.type from here, without having this value on the Translation object. -->
<property name="languageCode" type="string" column="language_code"/>
<property name="text" type="string"/>
</composite-element>
</bag>
</component>

翻译文本为 <many-to-one>

我设法通过映射 TranslatedText 获得接近我需要的东西作为 Question 内的实体使用<many-to-one>然后 map Translation作为 TranslatedText 内的值的集合,但这种方法的主要问题是没有简单的方法来摆脱孤儿 TranslatedTextTranslation 。我必须使用数据库触发器或计划进程来执行此操作。

结论

在这一点上,我的印象是 Hibernate 不够灵活,无法用正确的语义映射初始模型,但希望我是错的,并且有办法做到这一点。

最佳答案

我还没有找到将它们映射为值的方法。然而,下一个解决方案有效,并且可能对您有帮助。我删除了 TranslatedText 并将 Question 直接与 Translation 集合链接起来。

@Entity
public class Question {
@Id
private String id;

@JoinTable
@OrderColumn
@OneToMany(fetch = EAGER, cascade = ALL)
private List<Translation> titleTranslations;

@JoinTable
@OrderColumn
@OneToMany(fetch = EAGER, cascade = ALL)
private List<Translation> descriptionTranslations;
}

这里的缺点是 Translation 必须是 Entity 类。

@Entity
public class Translation {
@Id
private String id;
private String languageCode;
private String text;
}

关于java - 在 Hibernate 中映射复杂值对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42737289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com