【问题标题】:Can't figure out a one-to-many bidirectional association with join table无法确定与连接表的一对多双向关联
【发布时间】:2011-01-30 20:30:16
【问题描述】:

我试图弄清楚这个映射,但不知何故它只是在逃避我。这很烦人,因为这似乎应该是一个常见的情况。

我有一个基本的 Parent 和 Child 类,它们之间有一个连接表。 Child 类依赖于 Parent:如果 Child 从 Parent 中删除,则 Child 也应该被删除。 Hibernate 文档说这是通过指定 cascade="all,delete-orphan" 来实现的。

但架构不允许这样做。如果我使用 ,我无法指定列并且连接将不起作用。如果我根据 Hibernate 文档使用 ,则无法指定级联。

这是我现在所拥有的,取自Hibernate docs

<class name="Parent" table="parent_table">
    <id name="id" column="id">
        <generator class="assigned"/>
    </id>
    <property name="name" type="string"/>
    <list table="my_join_table" name="children">
        <key column="parent_id"/>
        <list-index column="idx">
        <!-- how do I put a cascade on this!? -->
        <many-to-many column="child_id" 
                      class="Child"
                      unique="true"/>
    </list>
</class>

<class name="Child" table="child_table">
    <id name="id" column="id">
        <generator class="assigned"/>
    </id>
    <property name="name" type="string"/>
    <join table="my_join_table" inverse="true" optional="false">
        <key column="child_id"/>
        <many-to-one name="parent" column="parent_id" not-null="true"/>
    </join>
</class>

【问题讨论】:

    标签: java hibernate orm join


    【解决方案1】:

    好吧,我自己终于弄明白了。

    级联属性需要放在列表元素上,而不是多对多:

     <list table="my_join_table" name="children" cascade="all,delete-orphan">
        <key column="parent_id"/>
        <list-index column="idx">
        <!-- how do I put a cascade on this!? -->
        <many-to-many column="child_id" 
                      class="Child"
                      unique="true"/>
    </list>
    

    【讨论】:

      猜你喜欢
      • 2021-07-24
      • 2012-03-10
      • 1970-01-01
      • 1970-01-01
      • 2018-09-04
      • 1970-01-01
      • 2010-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多