开发者

Hibernate Bi-Directional List Association

I'm sure there must be thousands of examples demonstrating this association but I can't seem to find one anywhere.

I have a one-many relationship from Parent-Child and a many-one relationship from Child-Parent:

class Parent {
    private Long id;
    private String name;
    private List<Child> children;
}

class Child {
    private Long id;
    private String name开发者_JAVA百科;
    private Parent parent;
}

I'm expecting to end up with 2 tables that look as follows:

Parent
 - id        : bigint
 - name      : varchar

Child
 - id        : bigint
 - parent_id : bigint
 - sequence  : bigint
 - name      : varchar

Have I got the right idea? If so does anyone know what I need to put in my mapping file so that when a parent is deleted so too are it's children.

Thanks in advance.

James


Found the solution in the end although I don't understand why I need insert="false" and update="false":

<hibernate-mapping>
    <class name="foo.Parent" table="Parent">
        <id name="id" type="int" column="id">
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String" column="name" length="50" />
        <list name="children" cascade="all">
            <key column="parent_id" />
            <index column="sequence" />
            <one-to-many class="foo.Child" />
        </list>
    </class>

    <class name="foo.Child" table="Child">
        <id name="id" type="int" column="id">
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String" column="name" length="50" />
        <many-to-one name="parent" class="foo.Parent" column="parent_id" insert="false" update="false" />
    </class>
</hibernate-mapping>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜