alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Hibernate example source code file (example_parentchild.xml)

This example Hibernate source code file (example_parentchild.xml) is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Java - Hibernate tags/keywords

cdata, cdata, child, child, hibernate, in, java, java, parent, the, the, this, xml, you

The Hibernate example_parentchild.xml source code

<?xml version='1.0' encoding="UTF-8"?>
<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
  ~ indicated by the @author tags or express copyright attribution
  ~ statements applied by the authors.  All third-party contributions are
  ~ distributed under license by Red Hat Middleware LLC.
  ~
  ~ This copyrighted material is made available to anyone wishing to use, modify,
  ~ copy, or redistribute it subject to the terms and conditions of the GNU
  ~ Lesser General Public License, as published by the Free Software Foundation.
  ~
  ~ This program is distributed in the hope that it will be useful,
  ~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  ~ or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
  ~ for more details.
  ~
  ~ You should have received a copy of the GNU Lesser General Public License
  ~ along with this distribution; if not, write to:
  ~ Free Software Foundation, Inc.
  ~ 51 Franklin Street, Fifth Floor
  ~ Boston, MA  02110-1301  USA
  -->

<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
<!ENTITY % BOOK_ENTITIES SYSTEM "../HIBERNATE_-_Relational_Persistence_for_Idiomatic_Java.ent">
%BOOK_ENTITIES;

]>

<chapter id="example-parentchild">
    <title>Example: Parent/Child

    <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 and Child 
        as entity classes with a <literal><one-to-many> association from Parent 
        to <literal>Child. The alternative approach is to declare the Child as a 
        <literal><composite-element>. 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 id="example-parentchild-collections">
        <title>A note about collections

        <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 id="example-parentchild-bidir">
        <title>Bidirectional one-to-many

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

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

        <programlisting role="JAVA">
    
        <para>
            Hibernate would issue two SQL statements:
        </para>

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

        <programlisting role="XML">
    <key column="parent_id" not-null="true"/>
    <one-to-many class="Child"/>
</set>]]>
    
        <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) 
            from <literal>p to c is not considered part of the state of the 
            <literal>Child object and is therefore not created in the INSERT. The 
            solution is to make the link part of the <literal>Child mapping.
        </para>

        <programlisting role="XML">]]>

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

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

        <programlisting role="XML">
    <key column="parent_id"/>
    <one-to-many class="Child"/>
</set>]]>

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

        <programlisting role="JAVA">

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

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

        <programlisting role="JAVA">

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

        <programlisting role="JAVA">

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

        <programlisting role="XML">
    <key column="parent_id"/>
    <one-to-many class="Child"/>
</set>]]>
     
         <para>
             This simplifies the code above to:
         </para>

        <programlisting role="JAVA">
     
         <para>
             Similarly, we do not need to iterate over the children when saving or deleting a <literal>Parent.
             The following removes <literal>p and all its children from the database.
         </para>

         <programlisting role="JAVA">
     
         <para>
             However, the following code:
         </para>

         <programlisting role="JAVA">
     
         <para>
             will not remove <literal>c from the database. In this case, it will only remove the link to p
             and cause a <literal>NOT NULL constraint violation. You need to explicitly
             <literal>delete() the Child.
         </para>

         <programlisting role="JAVA">

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

        <programlisting role="XML">
    <key column="parent_id"/>
    <one-to-many class="Child"/>
</set>]]>

         <para>
             Even though the collection mapping specifies <literal>inverse="true", 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().
         </para>
               
     </section>
     
     <section id="example-parentchild-update">
         <title>Cascades and unsaved-value
     
         <para>
             Suppose we loaded up a <literal>Parent in one Session, made some changes 
             in a UI action and wanted to persist these changes in a new session by calling <literal>update(). 
             The <literal>Parent 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 and Child have generated
             identifier properties of type <literal>Long. Hibernate will use the identifier and 
             version/timestamp property value to determine which of the children are new. (See
             <xref linkend="objectstate-saveorupdate"/>.) In Hibernate3, it is no longer necessary to specify
             an <literal>unsaved-value explicitly.
         </para>

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

         <programlisting role="JAVA">
     
         <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 id="example-parentchild-conclusion">
         <title>Conclusion

         <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><composite-element> 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>

Other Hibernate examples (source code examples)

Here is a short list of links related to this Hibernate example_parentchild.xml source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.