gpt4 book ai didi

java - 带有元数据的连接表的 hibernate 映射

转载 作者:行者123 更新时间:2023-12-04 05:25:56 26 4
gpt4 key购买 nike

我试图弄清楚如何通过包含一些元数据的连接表来映射两个表之间的关系。简而言之,这三个表代表一个表单的页面,每个页面可以包含任意数量的元素(问题)。出于某种原因,最初的开发人员决定元素可以用于多个表单。这意味着用于对页面上的元素进行排序的权重列位于连接表中。

enter image description here

我到底如何在 XML 中映射它? (注释不是一种选择。)

对于连接表,我猜是这样的:

<class name="com.foo.bar.model.db.ApplicationPageElements"  
table="APPLICATION_PAGE_ELEMENTS">
<composite-id name="id" class="com.foo.bar.model.db.ApplicationPageElementsKey">
<key-property name="pageId" column="page_id"/>
<key-property name="elementId" column="element_id"/>
</composite-id>
<property name="weight" type="java.lang.Long">
<column name="WEIGHT" precision="0" />
</property>
</class>

我的直觉让我想从 ApplicationPage 方面做这样的事情:
<set name="applicationElements" table="applicationPageElement">
<key column="page_id"/>
<many-to-many column="element_id" unique="true"
class="com.foo.bar.model.db.ApplicationElements" />
</set>

这就是我松懈下来,盯着屏幕,抽泣的地方。

我们使用 .hbm.xml 文件来映射我们的数据库。我们还决定不更改我们的数据库。

关于如何在 XML 中映射它的任何想法?

最佳答案

与其将 application_page 和 application_element 之间的关系视为多对多,不如将其视为从 application_page 到 ApplicationPageElements 的一对多关系以及从 application_element 到 ApplicationPageElements 的一对多关系。

在您的 application_page xml 映射中添加以下内容:

<set name="applicationElements" inverse="true">
<key column="page_id"/>
<one-to-many class="ApplicationPageElements"/>
</set>

page_id 构成连接表主键的一部分。因此,将集合标记为反向。

您对连接表的映射是正确的。但是,通过上述更改连接表的当前映射,您可以从 application_page 导航到 ApplicationPageElements。要从 application_page 导航到 application_element(通过 ApplicationPageElements),请在连接表映射中添加多对一关系。
<class name="com.foo.bar.model.db.ApplicationPageElements"  
table="APPLICATION_PAGE_ELEMENTS">
<composite-id name="id" class="com.foo.bar.model.db.ApplicationPageElementsKey">
<key-property name="pageId" column="page_id"/>
<key-property name="elementId" column="element_id"/>
</composite-id>
<property name="weight" type="java.lang.Long">
<column name="WEIGHT" precision="0" />
</property>
<many-to-one name="elements" class="ApplicationElements"
column="element_id" not-null="true" insert="false" update="false"/>
<many-to-one name="page" class="ApplicationPage"
column="page_id" not-null="true" insert="false" update="false"/>
</class>

注意在上面的多对一映射中,插入和更新属性设置为false。这是必要的,因为列被映射两次,一次在组合键中(负责插入值),另一次在多对一关联中。

上述用例在《Java Persistence with Hibernate》一书中有详细提到。

关于java - 带有元数据的连接表的 hibernate 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13202537/

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