代码之家  ›  专栏  ›  技术社区  ›  Laurent Grégoire

Hibernate与复合元素的自有集合的双向关系

  •  0
  • Laurent Grégoire  · 技术社区  · 7 年前

    我想在两个实体之间创建一个非常经典的双向父子关系。守则:

    public class History {
        public Long id;
        public List<HistoryField> fields;
    }
    
    public class HistoryField {
        public History history;
        public String foo, bar;
    }
    

    HistoryField 由其 History 父母亲

    <class name="History" table="history">
        <id name="id" type="long" />
        <list name="fields" cascade="all" table="fields">
            <key column="history_id" />
            <list-index column="order_index" />
            <composite-element class="HistoryField">
                <property name="foo" />
                <property name="bar" />
            </composite-element>
        </list>
    </class>
    

    但是 我如何指定 HistoryField::history 历史 ?

    这里的诀窍是集合是拥有的,并定义为一个复合元素(集合没有ID) 历史场 history_id + order_index ).这里不适用双向亲子关系的经典示例;因为它们解释了两个具有ID的类之间的关系,而这里拥有的类没有ID。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Alan Hay    7 年前

    文档中指出,您可以定义 <parent/> a的元素 <component/> 虽然它没有在由 <composite-element/> 我想这应该行得通。

    https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/components.html

    这个 <component> 元素允许 <parent> 映射一个元素的子元素 属性作为对包含 实体。

    因此:

    <class name="History" table="history">
        <id name="id" type="long" />
        <list name="fields" cascade="all" table="fields">
            <key column="history_id" />
            <list-index column="order_index" />
            <composite-element class="HistoryField">
                <!-- name of the property refeencing the containing entity -->
                <parent name="history"/>
                <property name="foo" />
                <property name="bar" />
            </composite-element>
        </list>
    </class>
    

    使用注释时 @Parent 注释可以类似地使用:

    https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#mapping-Parent

    冬眠特异性 @母公司 从可嵌入对象中删除所有者实体。

    @Embeddable
    public class HistoryField {
    
        @Parent
        public History history;
        public String foo, bar;
    }