<?xml version='1.0' encoding="UTF-8"?>

<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
  ~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
  -->
<chapter xml:id="example-parentchild" xmlns="http://docbook.org/ns/docbook">
    <title>Example: Parent/Child</title>

    <para>
        One of the first things that new users want to do with Hibernate is to model a parent/child type 
        relationship. There are two different approaches to this. The most convenient 
        approach, especially for new users, is to model both <literal>Parent</literal> and <literal>Child</literal> 
        as entity classes with a <literal>&lt;one-to-many&gt;</literal> association from <literal>Parent</literal> 
        to <literal>Child</literal>. The alternative approach is to declare the <literal>Child</literal> as a 
        <literal>&lt;composite-element&gt;</literal>. The default semantics of a one-to-many 
        association in Hibernate are much less close to the usual semantics of a parent/child relationship than 
        those of a composite element mapping. We will explain how to use a <emphasis>bidirectional one-to-many 
        association with cascades</emphasis> to model a parent/child relationship efficiently and elegantly. 
        
    </para>
    
    <section xml:id="example-parentchild-collections">
        <title>A note about collections</title>

        <para>
            Hibernate collections are considered to be a logical part of their owning entity and not of the
            contained entities. Be aware that this is a critical distinction that has the following consequences:
        </para>

        <itemizedlist>
            <listitem>
            <para>
                When you remove/add an object from/to a collection, the version number of the collection owner
                is incremented.
            </para>
            </listitem>
            <listitem>
            <para>
                If an object that was removed from a collection is an instance of a value type (e.g. a composite
                element), that object will cease to be persistent and its state will be completely removed from
                the database. Likewise, adding a value type instance to the collection will cause its state to be
                immediately persistent.
            </para>
            </listitem>
            <listitem>
            <para>
                Conversely, if an entity is removed from a collection (a one-to-many or many-to-many
                association), it will not be deleted by default. This behavior is completely consistent; a
                change to the internal state of another entity should not cause the associated entity to vanish.
                Likewise, adding an entity to a collection does not cause that entity to become persistent, by
                default.
            </para>
            </listitem>
        </itemizedlist>

        <para>
            Adding an entity to a collection, by default, merely creates a link between
            the two entities. Removing the entity will remove the link. This is appropriate for all sorts of cases.
            However, it is not appropriate in the case of a parent/child relationship. In this case, the life of the
            child is bound to the life cycle of the parent.
        </para>
    
    </section>

    <section xml:id="example-parentchild-bidir">
        <title>Bidirectional one-to-many</title>

        <para>
            Suppose we start with a simple <literal>&lt;one-to-many&gt;</literal> association from
            <literal>Parent</literal> to <literal>Child</literal>.
        </para>

        <programlisting role="XML"><![CDATA[<set name="children">
    <key column="parent_id"/>
    <one-to-many class="Child"/>
</set>]]></programlisting>
    
        <para>
            If we were to execute the following code:
        </para>

        <programlisting role="JAVA"><![CDATA[Parent p = .....;
Child c = new Child();
p.getChildren().add(c);
session.save(c);
session.flush();]]></programlisting>
    
        <para>
            Hibernate would issue two SQL statements:
        </para>

        <itemizedlist>
        <listitem>
            <para>an <literal>INSERT</literal> to create the record for <literal>c</literal></para>
        </listitem>
        <listitem>
            <para>
                an <literal>UPDATE</literal> to create the link from <literal>p</literal> to
                <literal>c</literal>
            </para>
        </listitem>
        </itemizedlist>
    
        <para>
            This is not only inefficient, but also violates any <literal>NOT NULL</literal> constraint on the
            <literal>parent_id</literal> column. You can fix the nullability constraint violation by specifying
            <literal>not-null="true"</literal> in the collection mapping:
        </para>

        <programlisting role="XML"><![CDATA[<set name="children">
    <key column="parent_id" not-null="true"/>
    <one-to-many class="Child"/>
</set>]]></programlisting>
    
        <para>
        	However, this is not the recommended solution.
       	</para>
       	<para>
            The underlying cause of this behavior is that the link (the foreign key <literal>parent_id</literal>) 
            from <literal>p</literal> to <literal>c</literal> is not considered part of the state of the 
            <literal>Child</literal> object and is therefore not created in the <literal>INSERT</literal>. The 
            solution is to make the link part of the <literal>Child</literal> mapping.
        </para>

        <programlisting role="XML"><![CDATA[<many-to-one name="parent" column="parent_id" not-null="true"/>]]></programlisting>

        <para>
            You also need to add the <literal>parent</literal> property to the <literal>Child</literal> class.
        </para>

        <para>
            Now that the <literal>Child</literal> entity is managing the state of the link, we tell the collection 
            not to update the link. We use the <literal>inverse</literal> attribute to do this:
        </para>

        <programlisting role="XML"><![CDATA[<set name="children" inverse="true">
    <key column="parent_id"/>
    <one-to-many class="Child"/>
</set>]]></programlisting>

        <para>
            The following code would be used to add a new <literal>Child</literal>:
        </para>

        <programlisting role="JAVA"><![CDATA[Parent p = (Parent) session.load(Parent.class, pid);
Child c = new Child();
c.setParent(p);
p.getChildren().add(c);
session.save(c);
session.flush();]]></programlisting>

        <para>
            Only one SQL <literal>INSERT</literal> would now be issued.
        </para>

        <para>
            You could also create an <literal>addChild()</literal> method of
            <literal>Parent</literal>.
        </para>

        <programlisting role="JAVA"><![CDATA[public void addChild(Child c) {
    c.setParent(this);
    children.add(c);
}]]></programlisting>

        <para>
            The code to add a <literal>Child</literal> looks like this:
        </para>

        <programlisting role="JAVA"><![CDATA[Parent p = (Parent) session.load(Parent.class, pid);
Child c = new Child();
p.addChild(c);
session.save(c);
session.flush();]]></programlisting>

     </section>
     
     <section xml:id="example-parentchild-cascades">
         <title>Cascading life cycle</title>
     
         <para>
             You can address the frustrations of the explicit call to <literal>save()</literal> by
             using cascades.
         </para>

        <programlisting role="XML"><![CDATA[<set name="children" inverse="true" cascade="all">
    <key column="parent_id"/>
    <one-to-many class="Child"/>
</set>]]></programlisting>
     
         <para>
             This simplifies the code above to:
         </para>

        <programlisting role="JAVA"><![CDATA[Parent p = (Parent) session.load(Parent.class, pid);
Child c = new Child();
p.addChild(c);
session.flush();]]></programlisting>
     
         <para>
             Similarly, we do not need to iterate over the children when saving or deleting a <literal>Parent</literal>.
             The following removes <literal>p</literal> and all its children from the database.
         </para>

         <programlisting role="JAVA"><![CDATA[Parent p = (Parent) session.load(Parent.class, pid);
session.delete(p);
session.flush();]]></programlisting>
     
         <para>
             However, the following code:
         </para>

         <programlisting role="JAVA"><![CDATA[Parent p = (Parent) session.load(Parent.class, pid);
Child c = (Child) p.getChildren().iterator().next();
p.getChildren().remove(c);
c.setParent(null);
session.flush();]]></programlisting>
     
         <para>
             will not remove <literal>c</literal> from the database. In this case, it will only remove the link to <literal>p</literal>
             and cause a <literal>NOT NULL</literal> constraint violation. You need to explicitly
             <literal>delete()</literal> the <literal>Child</literal>.
         </para>

         <programlisting role="JAVA"><![CDATA[Parent p = (Parent) session.load(Parent.class, pid);
Child c = (Child) p.getChildren().iterator().next();
p.getChildren().remove(c);
session.delete(c);
session.flush();]]></programlisting>

         <para>
             In our case, a <literal>Child</literal> cannot exist without its parent. So if we remove
             a <literal>Child</literal> from the collection, we do want it to be deleted. To do this, we must
             use <literal>cascade="all-delete-orphan"</literal>.
         </para>

        <programlisting role="XML"><![CDATA[<set name="children" inverse="true" cascade="all-delete-orphan">
    <key column="parent_id"/>
    <one-to-many class="Child"/>
</set>]]></programlisting>

         <para>
             Even though the collection mapping specifies <literal>inverse="true"</literal>, cascades are 
             still processed by iterating the collection elements. If you need an object be saved, 
             deleted or updated by cascade, you must add it to the collection. It is not enough to simply call
             <literal>setParent()</literal>.
         </para>
               
     </section>
     
     <section xml:id="example-parentchild-update">
         <title>Cascades and <literal>unsaved-value</literal></title>
     
         <para>
             Suppose we loaded up a <literal>Parent</literal> in one <literal>Session</literal>, made some changes 
             in a UI action and wanted to persist these changes in a new session by calling <literal>update()</literal>. 
             The <literal>Parent</literal> will contain a collection of children and, since the cascading update is enabled, 
             Hibernate needs to know which children are newly instantiated and which represent existing rows in the 
             database. We will also assume that both <literal>Parent</literal> and <literal>Child</literal> have generated
             identifier properties of type <literal>Long</literal>. Hibernate will use the identifier and 
             version/timestamp property value to determine which of the children are new. (See
             <xref linkend="objectstate-saveorupdate"/>.) <emphasis>In Hibernate, it is no longer necessary to specify
             an <literal>unsaved-value</literal> explicitly.</emphasis>
         </para>

         <para>
             The following code will update <literal>parent</literal> and <literal>child</literal> and insert 
             <literal>newChild</literal>:
         </para>

         <programlisting role="JAVA"><![CDATA[//parent and child were both loaded in a previous session
parent.addChild(child);
Child newChild = new Child();
parent.addChild(newChild);
session.update(parent);
session.flush();]]></programlisting>
     
         <para>
             This may be suitable for the case of a generated identifier, but what about assigned identifiers
             and composite identifiers? This is more difficult, since Hibernate cannot use the identifier property to
             distinguish between a newly instantiated object, with an identifier assigned by the user, and an 
             object loaded in a previous session. In this case, Hibernate will either use the timestamp or version 
             property, or will actually query the second-level cache or, worst case, the database, to see if the 
             row exists.
         </para>

     </section>

     <section xml:id="example-parentchild-conclusion">
         <title>Conclusion</title>

         <para>
             The sections we have just covered can be a bit confusing. However, in practice, 
             it all works out nicely. Most Hibernate applications use the parent/child pattern in many places.
         </para>

         <para>
             We mentioned an alternative in the first paragraph. None of the above issues exist in the case of
             <literal>&lt;composite-element&gt;</literal> mappings, which have exactly the semantics of a parent/child
             relationship. Unfortunately, there are two big limitations with composite element classes: composite elements 
             cannot own collections and they should not be the child of any entity other than the unique parent.
         </para>
     
     </section>
     
</chapter>
