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

Hibernate example source code file (example_mappings.xml)

This example Hibernate source code file (example_mappings.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

bigint, bigint, cdata, cdata, hibernate, in, lineitem, order, person, png, varchar, varchar, xml, xml

The Hibernate example_mappings.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-mappings">
    <title>Example: Various Mappings
   

    <para>
        This chapters explores some more complex association mappings.
    </para>
    
    <section id="example-mappings-emp">
        <title>Employer/Employee

        <para>
            The following model of the relationship between <literal>Employer and 
            <literal>Employee uses an entity class (Employment) 
            to represent the association. You can do this when there might be more than one
            period of employment for the same two parties. Components are used to model monetary 
            values and employee names.
        </para>

        <mediaobject>
            <imageobject role="html">
                <imagedata fileref="images/EmployerEmployee.png" format="PNG" align="center" />
            </imageobject>
            <imageobject role="fo">
                <imagedata fileref="images/EmployerEmployee.png" format="PNG" align="center" width="17cm" />
            </imageobject>
        </mediaobject>
        
        <para>
            Here is a possible mapping document:
        </para>
        
        <programlisting role="XML">
        
    <class name="Employer" table="employers">
        <id name="id">
            <generator class="sequence">
                <param name="sequence">employer_id_seq
            </generator>
        </id>
        <property name="name"/>
    </class>

    <class name="Employment" table="employment_periods">

        <id name="id">
            <generator class="sequence">
                <param name="sequence">employment_id_seq
            </generator>
        </id>
        <property name="startDate" column="start_date"/>
        <property name="endDate" column="end_date"/>

        <component name="hourlyRate" class="MonetaryAmount">
            <property name="amount">
                <column name="hourly_rate" sql-type="NUMERIC(12, 2)"/>
            </property>
            <property name="currency" length="12"/>
        </component>

        <many-to-one name="employer" column="employer_id" not-null="true"/>
        <many-to-one name="employee" column="employee_id" not-null="true"/>

    </class>

    <class name="Employee" table="employees">
        <id name="id">
            <generator class="sequence">
                <param name="sequence">employee_id_seq
            </generator>
        </id>
        <property name="taxfileNumber"/>
        <component name="name" class="Name">
            <property name="firstName"/>
            <property name="initial"/>
            <property name="lastName"/>
        </component>
    </class>

</hibernate-mapping>]]>

    <para>
        Here is the table schema generated by <literal>SchemaExport.
    </para>

    <programlisting>

    </section>
    
    <section id="example-mappings-authorwork">
        <title>Author/Work

        <para>
            Consider the following model of the relationships between <literal>Work,
            <literal>Author and Person. In the example, the relationship
            between <literal>Work and Author is represented as a many-to-many
            association and the relationship between <literal>Author 
            and <literal>Person is represented as one-to-one association. Another possibility would be to 
            have <literal>Author extend Person.  
        </para>

        <mediaobject>
            <imageobject role="html">
                <imagedata fileref="images/AuthorWork.png" format="PNG" align="center" />
            </imageobject>
            <imageobject role="fo">
                <imagedata fileref="images/AuthorWork.png" format="PNG" align="center" width="17cm" />
            </imageobject>
        </mediaobject>
        
        <para>
            The following mapping document correctly represents these relationships:
        </para>
        
        <programlisting role="XML">

    <class name="Work" table="works" discriminator-value="W">

        <id name="id" column="id">
            <generator class="native"/>
        </id>
        <discriminator column="type" type="character"/>

        <property name="title"/>
        <set name="authors" table="author_work">
            <key column name="work_id"/>
            <many-to-many class="Author" column name="author_id"/>
        </set>

        <subclass name="Book" discriminator-value="B">
            <property name="text"/>
        </subclass>

        <subclass name="Song" discriminator-value="S">
            <property name="tempo"/>
            <property name="genre"/>
        </subclass>

    </class>

    <class name="Author" table="authors">

        <id name="id" column="id">
            <!-- The Author must have the same identifier as the Person -->
            <generator class="assigned"/> 
        </id>

        <property name="alias"/>
        <one-to-one name="person" constrained="true"/>

        <set name="works" table="author_work" inverse="true">
            <key column="author_id"/>
            <many-to-many class="Work" column="work_id"/>
        </set>

    </class>

    <class name="Person" table="persons">
        <id name="id" column="id">
            <generator class="native"/>
        </id>
        <property name="name"/>
    </class>

</hibernate-mapping>]]>

    <para>
        There are four tables in this mapping: <literal>works,
        <literal>authors and persons hold work, author
        and person data respectively. <literal>author_work is an association
        table linking authors to works. Here is the table schema, as generated by
        <literal>SchemaExport:
    </para>

    <programlisting>

    </section>

    <section id="example-mappings-customerorderproduct">
        <title>Customer/Order/Product

        <para>
            In this section we consider a model of the relationships between <literal>Customer,
            <literal>Order, Line Item and Product.
            There is a one-to-many association between <literal>Customer and
            <literal>Order, but how can you represent Order / 
            <literal>LineItem / Product? In the example, 
            <literal>LineItem is mapped as an association class representing the many-to-many
            association between <literal>Order and Product. In
            Hibernate this is called a composite element.
        </para>

        <mediaobject>
            <imageobject role="html">
                <imagedata fileref="images/CustomerOrderProduct.png" format="PNG" align="center" />
            </imageobject>
            <imageobject role="fo">
                <imagedata fileref="images/CustomerOrderProduct.png" format="PNG" align="center" width="17cm" />
            </imageobject>
        </mediaobject>
        
        <para>
            The mapping document will look like this:
        </para>
        
        <programlisting role="XML">

    <class name="Customer" table="customers">
        <id name="id">
            <generator class="native"/>
        </id>
        <property name="name"/>
        <set name="orders" inverse="true">
            <key column="customer_id"/>
            <one-to-many class="Order"/>
        </set>
    </class>

    <class name="Order" table="orders">
        <id name="id">
            <generator class="native"/>
        </id>
        <property name="date"/>
        <many-to-one name="customer" column="customer_id"/>
        <list name="lineItems" table="line_items">
            <key column="order_id"/>
            <list-index column="line_number"/>
            <composite-element class="LineItem">
                <property name="quantity"/>
                <many-to-one name="product" column="product_id"/>
            </composite-element>
        </list>
    </class>

    <class name="Product" table="products">
        <id name="id">
            <generator class="native"/>
        </id>
        <property name="serialNumber"/>
    </class>

</hibernate-mapping>]]>

    <para>
        <literal>customers, orders, line_items and 
        <literal>products hold customer, order, order line item and product data
        respectively. <literal>line_items also acts as an association table linking
        orders with products.
    </para>

    <programlisting>

    </section>
    
    <section id="misc">
        <title>Miscellaneous example mappings
        
        <para>
            These examples are available from the Hibernate test suite. You
            will find many other useful example mappings there by searching in the
            <literal>test folder of the Hibernate distribution.
        </para>
        
      <!--  <-->
        
        <section id="example-mappings-typed-onetone">
            <title>"Typed" one-to-one association
<programlisting role="XML">
    <id name="name"/>
    <one-to-one name="address" 
            cascade="all">
        <formula>name
        <formula>'HOME'
    </one-to-one>
    <one-to-one name="mailingAddress" 
            cascade="all">
        <formula>name
        <formula>'MAILING'
    </one-to-one>
</class>

<class name="Address" batch-size="2" 
        check="addressType in ('MAILING', 'HOME', 'BUSINESS')">
    <composite-id>
        <key-many-to-one name="person" 
                column="personName"/>
        <key-property name="type" 
                column="addressType"/>
    </composite-id>
    <property name="street" type="text"/>
    <property name="state"/>
    <property name="zip"/>
</class>]]>
        </section>
        
        <section id="example-mappings-composite-key">
            <title>Composite key example
<programlisting role="XML">

    <id name="customerId"
        length="10">
        <generator class="assigned"/>
    </id>

    <property name="name" not-null="true" length="100"/>
    <property name="address" not-null="true" length="200"/>

    <list name="orders"
            inverse="true"
            cascade="save-update">
        <key column="customerId"/>
        <index column="orderNumber"/>
        <one-to-many class="Order"/>
    </list>

</class>

<class name="Order" table="CustomerOrder" lazy="true">
    <synchronize table="LineItem"/>
    <synchronize table="Product"/>
    
    <composite-id name="id" 
            class="Order$Id">
        <key-property name="customerId" length="10"/>
        <key-property name="orderNumber"/>
    </composite-id>
    
    <property name="orderDate" 
            type="calendar_date"
            not-null="true"/>
    
    <property name="total">
        <formula>
            ( select sum(li.quantity*p.price) 
            from LineItem li, Product p 
            where li.productId = p.productId 
                and li.customerId = customerId 
                and li.orderNumber = orderNumber )
        </formula>
    </property>
    
    <many-to-one name="customer"
            column="customerId"
            insert="false"
            update="false" 
            not-null="true"/>
        
    <bag name="lineItems"
            fetch="join" 
            inverse="true"
            cascade="save-update">
        <key>
            <column name="customerId"/>
            <column name="orderNumber"/>
        </key>
        <one-to-many class="LineItem"/>
    </bag>
    
</class>
    
<class name="LineItem">
    
    <composite-id name="id" 
            class="LineItem$Id">
        <key-property name="customerId" length="10"/>
        <key-property name="orderNumber"/>
        <key-property name="productId" length="10"/>
    </composite-id>
    
    <property name="quantity"/>
    
    <many-to-one name="order"
            insert="false"
            update="false" 
            not-null="true">
        <column name="customerId"/>
        <column name="orderNumber"/>
    </many-to-one>
    
    <many-to-one name="product"
            insert="false"
            update="false" 
            not-null="true"
            column="productId"/>
        
</class>

<class name="Product">
    <synchronize table="LineItem"/>

    <id name="productId"
        length="10">
        <generator class="assigned"/>
    </id>
    
    <property name="description" 
        not-null="true" 
        length="200"/>
    <property name="price" length="3"/>
    <property name="numberAvailable"/>
    
    <property name="numberOrdered">
        <formula>
            ( select sum(li.quantity) 
            from LineItem li 
            where li.productId = productId )
        </formula>
    </property>
    
</class>]]>
        </section>
        
        <section id="example-mappings-composite-key-manytomany">
            <title>Many-to-many with shared composite key attribute
<programlisting role="XML">
    <composite-id>
        <key-property name="name"/>
        <key-property name="org"/>
    </composite-id>
    <set name="groups" table="UserGroup">
        <key>
            <column name="userName"/>
            <column name="org"/>
        </key>
        <many-to-many class="Group">
            <column name="groupName"/>
            <formula>org
        </many-to-many>
    </set>
</class>
    
<class name="Group" table="`Group`">
    <composite-id>
        <key-property name="name"/>
        <key-property name="org"/>
    </composite-id>
    <property name="description"/>
    <set name="users" table="UserGroup" inverse="true">
        <key>
            <column name="groupName"/>
            <column name="org"/>
        </key>
        <many-to-many class="User">
            <column name="userName"/>
            <formula>org
        </many-to-many>
    </set>
</class>
]]></programlisting>
        </section>

        <section id="example-mappings-content-discrimination">
            <title>Content based discrimination
<programlisting role="XML">
        </section>

        <section id="example-mappings-association-alternatekeys" revision="2">
            <title>Associations on alternate keys
<programlisting role="XML">
    
    <id name="id">
        <generator class="hilo"/>
    </id>
    
    <property name="name" length="100"/>
    
    <one-to-one name="address" 
        property-ref="person"
        cascade="all"
        fetch="join"/>
    
    <set name="accounts" 
        inverse="true">
        <key column="userId"
            property-ref="userId"/>
        <one-to-many class="Account"/>
    </set>
    
    <property name="userId" length="8"/>

</class>

<class name="Address">

    <id name="id">
        <generator class="hilo"/>
    </id>

    <property name="address" length="300"/>
    <property name="zip" length="5"/>
    <property name="country" length="25"/>
    <many-to-one name="person" unique="true" not-null="true"/>

</class>

<class name="Account">
    <id name="accountId" length="32">
        <generator class="uuid"/>
    </id>
    
    <many-to-one name="user"
        column="userId"
        property-ref="userId"/>
    
    <property name="type" not-null="true"/>
    
</class>]]>
        </section>

    </section>

</chapter>

Other Hibernate examples (source code examples)

Here is a short list of links related to this Hibernate example_mappings.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.