<html><head>
      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
   <title>HIBERNATE - Relational Persistence for Idiomatic Java</title><link rel="stylesheet" href="../styles/html.css" type="text/css"><meta name="generator" content="DocBook XSL Stylesheets V1.60.1"></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div class="book" lang="en"><div class="titlepage"><div><div><h1 class="title"><a name="d0e1"></a>HIBERNATE - Relational Persistence for Idiomatic Java</h1></div><div><h2 class="subtitle">Hibernate2 Reference Documentation</h2></div><div><p class="releaseinfo">2.0.2</p></div></div><div></div><hr></div><div class="toc"><p><b>Table of Contents</b></p><dl><dt>1. <a href="#architecture">Architecture</a></dt><dd><dl><dt>1.1. <a href="#architecture-s1">Overview</a></dt><dt>1.2. <a href="#architecture-s2">Persistent Object Identity</a></dt><dt>1.3. <a href="#architecture-s3">JMX Integration</a></dt><dt>1.4. <a href="#architecture-s4">JCA Support</a></dt></dl></dd><dt>2. <a href="#session-configuration">SessionFactory Configuration</a></dt><dd><dl><dt>2.1. <a href="#session-configuration-s1">Programmatic Configuration</a></dt><dt>2.2. <a href="#session-configuration-s2">Obtaining a SessionFactory</a></dt><dt>2.3. <a href="#session-configuration-s3">User provided JDBC connection</a></dt><dt>2.4. <a href="#session-configuration-s4">Hibernate provided JDBC connection</a></dt><dt>2.5. <a href="#session-configuration-s5">Other properties</a></dt><dd><dl><dt>2.5.1. <a href="#session-configuration-s5-1">SQL Dialects</a></dt><dt>2.5.2. <a href="#session-configuration-s5-2">Outer Join Fetching</a></dt><dt>2.5.3. <a href="#session-configuration-s5-3">Binary Streams</a></dt><dt>2.5.4. <a href="#session-configuration-s5-4">SQL Logging to Console</a></dt><dt>2.5.5. <a href="#session-configuration-s5-5">Custom ConnectionProvider</a></dt><dt>2.5.6. <a href="#session-configuration-s5-6">Transaction Strategy</a></dt><dt>2.5.7. <a href="#session-configuration-s5-7">JNDI-bound SessionFactory</a></dt><dt>2.5.8. <a href="#session-configuration-s5-8">Query Language Substitution</a></dt></dl></dd><dt>2.6. <a href="#session-configuration-s6">XML Configuration File</a></dt><dt>2.7. <a href="#session-configuration-s7">Logging</a></dt></dl></dd><dt>3. <a href="#persistent-classes">Persistent Classes</a></dt><dd><dl><dt>3.1. <a href="#persistent-classes-s1">Simple Example</a></dt><dd><dl><dt>3.1.1. <a href="#persistent-classes-s1-1">Declare accessors and mutators for persistent fields</a></dt><dt>3.1.2. <a href="#persistent-classes-s1-2">Implement a default constructor</a></dt><dt>3.1.3. <a href="#persistent-classes-s1-3">Provide an identifier property (optional)</a></dt></dl></dd><dt>3.2. <a href="#persistent-classes-s2">Inheritance</a></dt><dt>3.3. <a href="#persistent-classes-s3">Persistent Lifecycle Callbacks</a></dt><dt>3.4. <a href="#persistent-classes-s4">Validatable</a></dt><dt>3.5. <a href="#persistent-classes-s5">XDoclet Example</a></dt></dl></dd><dt>4. <a href="#or-mapping">Basic O/R Mapping</a></dt><dd><dl><dt>4.1. <a href="#or-mapping-s1">Mapping declaration</a></dt><dd><dl><dt>4.1.1. <a href="#or-mapping-s1-1">Doctype</a></dt><dt>4.1.2. <a href="#or-mapping-s1-2">hibernate-mapping</a></dt><dt>4.1.3. <a href="#or-mapping-s1-3">class</a></dt><dt>4.1.4. <a href="#or-mapping-s1-4">id</a></dt><dd><dl><dt>4.1.4.1. <a href="#or-mapping-s1-4--generator">generator</a></dt><dt>4.1.4.2. <a href="#or-mapping-s1-4-hilo">Hi/Lo Algorithm</a></dt><dt>4.1.4.3. <a href="#or-mapping-s1-4-uuid">UUID Algorithm</a></dt><dt>4.1.4.4. <a href="#or-mapping-s1-4-sequences">Identity Columns and Sequences</a></dt><dt>4.1.4.5. <a href="#or-mapping-s1-4-assigned">Assigned Identifiers</a></dt></dl></dd><dt>4.1.5. <a href="#or-mapping-s1-4b">composite-id</a></dt><dt>4.1.6. <a href="#or-mapping-s1-5">discriminator</a></dt><dt>4.1.7. <a href="#or-mapping-s1-6">version (optional)</a></dt><dt>4.1.8. <a href="#or-mapping-s1-6b">timestamp (optional)</a></dt><dt>4.1.9. <a href="#or-mapping-s1-7">property</a></dt><dt>4.1.10. <a href="#or-mapping-s1-8">many-to-one</a></dt><dt>4.1.11. <a href="#or-mapping-s1-9">one-to-one</a></dt><dt>4.1.12. <a href="#or-mapping-s1-10">component, dynabean</a></dt><dt>4.1.13. <a href="#or-mapping-s1-11">subclass</a></dt><dt>4.1.14. <a href="#or-mapping-s1-11b">joined-subclass</a></dt><dt>4.1.15. <a href="#or-mapping-s1-12">map, set, list, bag</a></dt><dt>4.1.16. <a href="#or-mapping-s1-13">import</a></dt></dl></dd><dt>4.2. <a href="#or-mapping-s2">Hibernate Types</a></dt><dd><dl><dt>4.2.1. <a href="#or-mapping-s2-1">Entities and values</a></dt><dt>4.2.2. <a href="#or-mapping-s2-2">Basic value types</a></dt><dt>4.2.3. <a href="#or-mapping-s2-3">Persistent enum types</a></dt><dt>4.2.4. <a href="#or-mapping-s2-4">Custom value types</a></dt><dt>4.2.5. <a href="#or-mapping-s2-5">Any type mappings</a></dt></dl></dd><dt>4.3. <a href="#or-mapping-s3">SQL quoted identifiers</a></dt><dt>4.4. <a href="#or-mapping-s4">Customizing the DDL</a></dt></dl></dd><dt>5. <a href="#collections">Collections</a></dt><dd><dl><dt>5.1. <a href="#collections-s1-1">Persistent Collections</a></dt><dt>5.2. <a href="#collections-s1-3">Mapping a Collection</a></dt><dt>5.3. <a href="#collections-s1-5">Collections of Values and Many To Many Associations</a></dt><dt>5.4. <a href="#collections-s1-6">One To Many Associations</a></dt><dt>5.5. <a href="#collections-s1-7">Lazy Initialization</a></dt><dt>5.6. <a href="#collections-s1-8a">Sorted Collections</a></dt><dt>5.7. <a href="#collections-s1-8b">Other Ways To Sort a Collection</a></dt><dt>5.8. <a href="#collections-s1-9">Garbage Collection</a></dt><dt>5.9. <a href="#collections-s1-10">Bidirectional Associations</a></dt><dt>5.10. <a href="#collections-s1-11a">Ternary Associations</a></dt><dt>5.11. <a href="#collections-s1-11b">Heterogeneous Associations</a></dt><dt>5.12. <a href="#collections-s1-12">Collection Example</a></dt><dt>5.13. <a href="#collections-s1-13">&lt;idbag&gt;</a></dt></dl></dd><dt>6. <a href="#components">Components</a></dt><dd><dl><dt>6.1. <a href="#components-s2-1">As Dependent Objects</a></dt><dt>6.2. <a href="#components-s2-2">In Collections</a></dt><dt>6.3. <a href="#components-s2-2b">As a Map Index</a></dt><dt>6.4. <a href="#components-s2-3">As Composite Identifiers</a></dt><dt>6.5. <a href="#components-s2-4">Dynabean components</a></dt></dl></dd><dt>7. <a href="#manipulating-data">Manipulating Persistent Data</a></dt><dd><dl><dt>7.1. <a href="#manipulating-data-s1">Creating a persistent object</a></dt><dt>7.2. <a href="#manipulating-data-s2">Loading an object</a></dt><dt>7.3. <a href="#manipulating-data-s3">Querying</a></dt><dd><dl><dt>7.3.1. <a href="#manipulating-data-s4">Scalar queries</a></dt><dt>7.3.2. <a href="#manipulating-data-s5">The Query interface</a></dt><dt>7.3.3. <a href="#manipulating-data-s5b">Scrollable iteration</a></dt><dt>7.3.4. <a href="#manipulating-data-s6">Filtering collections</a></dt></dl></dd><dt>7.4. <a href="#manipulating-data-s7">Updating objects saved or loaded in the current session</a></dt><dt>7.5. <a href="#manipulating-data-s8">Updating objects saved or loaded in a previous session</a></dt><dt>7.6. <a href="#manipulating-data-s9">Deleting persistent objects</a></dt><dt>7.7. <a href="#manipulating-data-s10">Graphs of objects</a></dt><dd><dl><dt>7.7.1. <a href="#manipulating-data-s11a">Lifecycle objects</a></dt><dt>7.7.2. <a href="#manipulating-data-s11b">Persistence by Reachability</a></dt></dl></dd><dt>7.8. <a href="#manipulating-data-s12">Flushing</a></dt><dt>7.9. <a href="#manipulating-data-s13">Ending a Session</a></dt><dd><dl><dt>7.9.1. <a href="#manipulating-data-s13-1">Flushing the session</a></dt><dt>7.9.2. <a href="#manipulating-data-s13-2">Committing the transaction</a></dt><dt>7.9.3. <a href="#manipulating-data-s13-3">Closing the session</a></dt><dt>7.9.4. <a href="#manipulating-data-s13-4">Exception handling</a></dt></dl></dd><dt>7.10. <a href="#manipulating-data-s15">Interceptors</a></dt><dt>7.11. <a href="#manipulating-data-s16">Metadata API</a></dt></dl></dd><dt>8. <a href="#parent-child">Parent Child Relationships</a></dt><dd><dl><dt>8.1. <a href="#parent-child-collections">A note about collections</a></dt><dt>8.2. <a href="#parent-child-bidir">Bidirectional one to many</a></dt><dt>8.3. <a href="#parent-child-cascades">Cascades</a></dt><dt>8.4. <a href="#parent-child-update">Using cascading update()</a></dt><dt>8.5. <a href="#parent-child-conclusion">Conclusion</a></dt></dl></dd><dt>9. <a href="#query-language">Hibernate Query Language</a></dt><dd><dl><dt>9.1. <a href="#query-language-s1">Case Sensitivity</a></dt><dt>9.2. <a href="#query-language-s2">The from clause</a></dt><dt>9.3. <a href="#query-language-s3">Associations and joins</a></dt><dt>9.4. <a href="#query-language-s4">The select clause</a></dt><dt>9.5. <a href="#query-language-s4a">Aggregate functions</a></dt><dt>9.6. <a href="#query-language-s4b">polymorphism</a></dt><dt>9.7. <a href="#query-language-s5">The where clause</a></dt><dt>9.8. <a href="#query-language-s6">Expressions</a></dt><dt>9.9. <a href="#query-language-s7">The order by clause</a></dt><dt>9.10. <a href="#query-language-s8">The group by clause</a></dt><dt>9.11. <a href="#query-language-s9">Subqueries</a></dt><dt>9.12. <a href="#query-language-s10">Examples</a></dt><dt>9.13. <a href="#query-language-s11">Tips &amp; Tricks</a></dt></dl></dd><dt>10. <a href="#worked-example">A Worked Example</a></dt><dd><dl><dt>10.1. <a href="#worked-example-classes">Persistent Classes</a></dt><dt>10.2. <a href="#worked-example-mappings">Hibernate Mappings</a></dt><dt>10.3. <a href="#worked-example-code">Hibernate Code</a></dt></dl></dd><dt>11. <a href="#performance">Improving Performance</a></dt><dd><dl><dt>11.1. <a href="#performance-s4">Proxies for Lazy Initialization</a></dt><dt>11.2. <a href="#performance-s3">Process Level Cache</a></dt><dd><dl><dt>11.2.1. <a href="#performance-s3-1">Mapping</a></dt><dt>11.2.2. <a href="#performance-s3-2">Read Only Cache</a></dt><dt>11.2.3. <a href="#performance-s3-3">Read / Write Cache</a></dt><dt>11.2.4. <a href="#performance-s3-4">Nonstrict Read / Write Cache</a></dt></dl></dd><dt>11.3. <a href="#performance-s5">Managing the Session Cache</a></dt></dl></dd><dt>12. <a href="#collection-performance">Understanding Collection Performance</a></dt><dd><dl><dt>12.1. <a href="#collection-performance-taxonomy">Taxonomy</a></dt><dt>12.2. <a href="#collection-performance-mostefficient-1">Lists, maps and sets are the most efficient collections to update</a></dt><dt>12.3. <a href="#collection-performance-mostefficient-2">Bags and lists are the most efficient inverse collections</a></dt><dt>12.4. <a href="#collection-performance-oneshotdelete">One shot delete</a></dt></dl></dd><dt>13. <a href="#query-criteria">Criteria Queries</a></dt><dd><dl><dt>13.1. <a href="#query-criteria-s1">Creating a Criteria instance</a></dt><dt>13.2. <a href="#query-criteria-s2">Narrowing the result set</a></dt><dt>13.3. <a href="#query-criteria-s3">Ordering the results</a></dt><dt>13.4. <a href="#query-criteria-s4">Dynamic association fetching</a></dt></dl></dd><dt>14. <a href="#transactions">Transactions And Concurrency</a></dt><dd><dl><dt>14.1. <a href="#transactions-s1">Configurations, Sessions and Factories</a></dt><dt>14.2. <a href="#transactions-s2">Threads and connections</a></dt><dt>14.3. <a href="#transactions-s3">Optimistic Locking / Versioning</a></dt><dd><dl><dt>14.3.1. <a href="#transactions-s3-1">Long session with automatic versioning</a></dt><dt>14.3.2. <a href="#transactions-s3-2">Many sessions with automatic versioning</a></dt><dt>14.3.3. <a href="#transactions-s3-3">Application version checking</a></dt></dl></dd><dt>14.4. <a href="#transactions-s4">Session disconnection</a></dt><dt>14.5. <a href="#transactions-s5">Pessimistic Locking</a></dt></dl></dd><dt>15. <a href="#examples">Mapping Examples</a></dt><dd><dl><dt>15.1. <a href="#examples-s0">Employer/Employee</a></dt><dt>15.2. <a href="#examples-s1">Author/Work</a></dt><dt>15.3. <a href="#examples-s2">Customer/Order/Product</a></dt></dl></dd><dt>16. <a href="#best-practices">Best Practices</a></dt><dt>17. <a href="#toolsetguide">Toolset Guide</a></dt><dd><dl><dt>17.1. <a href="#toolsetguide-s1">Schema Generation</a></dt><dd><dl><dt>17.1.1. <a href="#toolsetguide-s1-2">Customizing the schema</a></dt><dt>17.1.2. <a href="#toolsetguide-s1-3">Running the tool</a></dt><dt>17.1.3. <a href="#toolsetguide-s1-4">Properties</a></dt><dt>17.1.4. <a href="#toolsetguide-s1-5">Using Ant</a></dt><dt>17.1.5. <a href="#toolsetguide-s1-6">Incremental schema updates</a></dt><dt>17.1.6. <a href="#toolsetguide-s1-7">Using Ant for incremental schema updates</a></dt></dl></dd><dt>17.2. <a href="#toolsetguide-s2">Code Generation</a></dt><dd><dl><dt>17.2.1. <a href="#toolsetguide-s2-1">The config file (optional)</a></dt><dt>17.2.2. <a href="#toolsetguide-s2-2">The meta attribute</a></dt><dt>17.2.3. <a href="#toolsetguide-s2-3">Basic finder generator</a></dt></dl></dd><dt>17.3. <a href="#toolsetguide-s3">Mapping File Generation</a></dt><dd><dl><dt>17.3.1. <a href="#toolsetguide-s3-1">Running the tool</a></dt></dl></dd></dl></dd></dl></div><div class="chapter" lang="en"><div class="titlepage"><div><div><h2 class="title"><a name="architecture"></a>Chapter&nbsp;1.&nbsp;Architecture</h2></div></div><div></div></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="architecture-s1"></a>1.1.&nbsp;Overview</h2></div></div><div></div></div><p>

            A (very) high-level view of the Hibernate architecture:

            subelement that maps a property of the component class as a reference back to the
            containing entity.
        </p><pre class="programlisting">&lt;class name="eg.Person" table="person"&gt;
    &lt;id name="Key" column="pid" type="string"&gt;
        &lt;generator class="uuid.hex"/&gt;
    &lt;/id&gt;
    &lt;property name="birthday" type="date"/&gt;
    &lt;component name="Name" class="eg.Name"&gt;

        &lt;parent name="namedPerson"/&gt; &lt;!-- reference back to the Person --&gt;
        &lt;property name="initial"/&gt;
        &lt;property name="first"/&gt;
        &lt;property name="last"/&gt;
    &lt;/component&gt;

&lt;/class&gt;</pre></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="components-s2-2"></a>6.2.&nbsp;In Collections</h2></div></div><div></div></div><p>
            Collections of components are supported (eg. an array of type
            <tt class="literal">Name</tt>). Declare your component collection by
            replacing the <tt class="literal">&lt;element&gt;</tt> tag with a
            <tt class="literal">&lt;composite-element&gt;</tt> tag.
        </p><pre class="programlisting">&lt;set name="someNames" table="some_names" lazy="true"&gt;
    &lt;key column="id"/&gt;

    &lt;composite-element class="eg.Name"&gt; &lt;!-- class attribute required --&gt;
        &lt;property name="initial"/&gt;
        &lt;property name="first"/&gt;
        &lt;property name="last"/&gt;
    &lt;/composite-element&gt;

&lt;/set&gt;</pre><p>
            Composite elements may contain components but not collections. If your
            composite element itself contains 
            components, use the <tt class="literal">&lt;nested-composite-element&gt;</tt> 
            tag. This is a pretty exotic case - a collection of components which 
            themselves have components. By this stage you should be asking yourself 
            if a one-to-many association is more appropriate. Try remodelling the 
            composite element as an entity - but note that even though the Java model 
            is the same, the relational model and persistence semantics are still 
            slightly different.
        </p><p>
            Please note that a composite element mapping doesn't support null-able properties
            if you're using a <tt class="literal">&lt;set&gt;</tt>. Hibernate
            has to use each columns value to identify a record when deleting objects
            (there is no separate primary key column in the composite element table),
            which is not possible with null values. You have to either use only
            not-null properties in a composite-element or choose a
            <tt class="literal">&lt;list&gt;</tt>, <tt class="literal">&lt;map&gt;</tt>,
            <tt class="literal">&lt;bag&gt;</tt> or <tt class="literal">&lt;idbag&gt;</tt>.
        </p><p>

            A special case of a composite element is a composite element with a nested
            <tt class="literal">&lt;many-to-one&gt;</tt> element. A mapping like this allows
            you to map extra columns of a many-to-many association table to the
            composite element class. The following is a many-to-many association
            from <tt class="literal">Order</tt> to <tt class="literal">Item</tt> where 
            <tt class="literal">purchaseDate</tt>, <tt class="literal">price</tt> and
            <tt class="literal">quantity</tt> are properties of the association:
        </p><pre class="programlisting">&lt;class name="eg.Order" .... &gt;

    ....
    &lt;set name="purchasedItems" table="purchase_items" lazy="true"&gt;
        &lt;key column="order_id"&gt;
        &lt;composite-element class="eg.Purchase"&gt;
            &lt;property name="purchaseDate"/&gt;
            &lt;property name="price"/&gt;
            &lt;property name="quantity"/&gt;

            &lt;many-to-one name="item" class="eg.Item"/&gt; &lt;!-- class attribute is optional --&gt;
        &lt;/composite-element&gt;
    &lt;/set&gt;
&lt;/class&gt;</pre><p>Even ternary (or quaternary, etc) associations are possible:</p><pre class="programlisting">&lt;class name="eg.Order" .... &gt;
    ....
    &lt;set name="purchasedItems" table="purchase_items" lazy="true"&gt;

        &lt;key column="order_id"&gt;
        &lt;composite-element class="eg.OrderLine"&gt;
            &lt;many-to-one name="purchaseDetails class="eg.Purchase"/&gt;
            &lt;many-to-one name="item" class="eg.Item"/&gt;
        &lt;/composite-element&gt;
    &lt;/set&gt;

&lt;/class&gt;</pre><p>Composite element properties may not appear in a query, unfortunately.</p></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="components-s2-2b"></a>6.3.&nbsp;As a Map Index</h2></div></div><div></div></div><p>
            The <tt class="literal">&lt;composite-index&gt;</tt> element lets you map a
            component class as the key of a <tt class="literal">Map</tt>. Make sure you override
            <tt class="literal">hashCode()</tt> and <tt class="literal">equals()</tt> correctly on
            the component class.
        </p></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="components-s2-3"></a>6.4.&nbsp;As Composite Identifiers</h2></div></div><div></div></div><p>

            You may use a component as an identifier of an entity class. Your component
            class must satisfy certain requirements:
        </p><div class="itemizedlist"><ul type="disc" compact><li><p>
                    It must implement <tt class="literal">java.io.Serializable</tt>.
                </p></li><li><p>
                    It must re-implement <tt class="literal">equals()</tt> and
                    <tt class="literal">hashCode()</tt>, consistently with the database's 
                    notion of composite key equality.
                </p></li></ul></div><p>
            You can't use an <tt class="literal">IdentifierGenerator</tt> to generate composite keys.
            Instead the application must assign its own identifiers.
        </p><p>

            Since a composite identifier must be assigned to the object before saving it,
            we can't use <tt class="literal">unsaved-value</tt> to distinguish between newly
            instantiated instances and instances saved in a previous session. You should
            instead implement <tt class="literal">Interceptor.isUnsaved()</tt> if you wish
            to use <tt class="literal">saveOrUpdate()</tt> or cascading save / update.
        </p><p>
            Use the <tt class="literal">&lt;composite-id&gt;</tt> tag (same attributes and
            elements as <tt class="literal">&lt;component&gt;</tt>) in place of
            <tt class="literal">&lt;id&gt;</tt>. Declaration of a composite identifier
            class looks like:
        </p><pre class="programlisting">&lt;class name="eg.Foo" table"FOOS"&gt;

    &lt;composite-id name="compId" class="eg.FooCompositeID"&gt;
        &lt;key-property name="string"/&gt;
        &lt;key-property name="short"/&gt;
        &lt;key-property name="date" column="date_" type="date"/&gt;
    &lt;/composite-id&gt;
    &lt;property name="name"/&gt;

    ....
&lt;/class&gt;</pre><p>
            Now, any foreign keys into the table <tt class="literal">FOOS</tt> are also composite.
            You must declare this in your mappings for other classes. An association to
            <tt class="literal">Foo</tt> would be declared like this:
        </p><pre class="programlisting">&lt;many-to-one name="foo" class="eg.Foo"&gt;
&lt;!-- the "class" attribute is optional, as usual --&gt;
    &lt;column name="foo_string"/&gt;

    &lt;column name="foo_short"/&gt;
    &lt;column name="foo_date"/&gt;
&lt;/many-to-one&gt;</pre><p>
        This new <tt class="literal">&lt;column&gt;</tt> tag is also used by multi-column custom types.
        Actually it is an alternative to the <tt class="literal">column</tt> attribute everywhere. A
        collection with elements of type <tt class="literal">Foo</tt> would use:
    </p><pre class="programlisting">&lt;set name="foos"&gt;

    &lt;key column="owner_id"/&gt;
    &lt;many-to-many class="eg.Foo"&gt;
        &lt;column name="foo_string"/&gt;
        &lt;column name="foo_short"/&gt;
        &lt;column name="foo_date"/&gt;
    &lt;/many-to-many&gt;

&lt;/set&gt;</pre><p>
            On the other hand, <tt class="literal">&lt;one-to-many&gt;</tt>, as usual, declares no columns.
        </p><p>
            If <tt class="literal">Foo</tt> itself contains collections, they will also need a
            composite foreign key.
        </p><pre class="programlisting">&lt;class name="eg.Foo"&gt;
    ....
    ....
    &lt;set name="dates" lazy="true"&gt;

        &lt;key&gt;   &lt;!-- a collection inherits the composite key type --&gt;
            &lt;column name="foo_string"/&gt;
            &lt;column name="foo_short"/&gt;
            &lt;column name="foo_date"/&gt;
        &lt;/key&gt;

        &lt;element column="foo_date" type="date"/&gt;
    &lt;/set&gt;
&lt;/class&gt;</pre></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="components-s2-4"></a>6.5.&nbsp;Dynabean components</h2></div></div><div></div></div><p>
            You may even map a property of type <tt class="literal">DynaBean</tt>:
        </p><pre class="programlisting">&lt;dynabean name="userAttributes" dynaclass="UserAttributes"&gt;
    &lt;property name="foo" column="FOO"/&gt;

    &lt;property name="bar" column="BAR"/&gt;
    &lt;many-to-one name="baz" class="eg.Baz" column="BAZ"/&gt;
&lt;/dynabean&gt;</pre><p>
            The semantics of a <tt class="literal">&lt;dynabean&gt;</tt> mapping are identical
            to <tt class="literal">&lt;component&gt;</tt>. The advantage of this kind of mapping
            is the ability to determine the actual properties of the bean at deployment time
            by editting the mapping document. (Runtime manipulation of the mapping document
            is also possible, using a DOM parser.)
        </p></div></div><div class="chapter" lang="en"><div class="titlepage"><div><div><h2 class="title"><a name="manipulating-data"></a>Chapter&nbsp;7.&nbsp;Manipulating Persistent Data</h2></div></div><div></div></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="manipulating-data-s1"></a>7.1.&nbsp;Creating a persistent object</h2></div></div><div></div></div><p>

            An object (entity instance) is either <span class="emphasis"><em>transient</em></span> or
            <span class="emphasis"><em>persistent</em></span> with respect to a particular
            <tt class="literal">Session</tt>. Newly instantiated objects are, of course, transient. 
            The session offers services for saving (ie. persisting) transient instances:
        </p><pre class="programlisting">DomesticCat fritz = new DomesticCat();
fritz.setColor(Color.GINGER);
fritz.setSex('M');
fritz.setName("Fritz");
Long generatedId = (Long) sess.save(fritz);</pre><pre class="programlisting">DomesticCat pk = new DomesticCat();
pk.setColor(Color.TABBY);
pk.setSex('F');
pk.setName("PK");
pk.setKittens( new HashSet() );
pk.addKitten(fritz);
sess.save( pk, new Long(1234) );</pre><p>
            The single-argument <tt class="literal">save()</tt> generates and assigns a unique
            identifier to <tt class="literal">fritz</tt>. The two-argument form attempts to persist
            <tt class="literal">pk</tt> using the given identifier. We generally discourage the use of 
            the two-argument form since it may be used to create primary keys with business meaning.
            It is most useful in certain special situations like using Hibernate to persist a BMP 
            entity bean.
        </p><p>

            Associated objects may be made persistent in any order you like unless you 
            have a <tt class="literal">NOT NULL</tt> constraint upon a foreign key column.
            There is never a risk of violating foreign key constraints. However, you 
            might violate a <tt class="literal">NOT NULL</tt> constraint if you
            <tt class="literal">save()</tt> the objects in the wrong order.
        </p></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="manipulating-data-s2"></a>7.2.&nbsp;Loading an object</h2></div></div><div></div></div><p>
            The <tt class="literal">load()</tt> methods of <tt class="literal">Session</tt> give you 
            a way to retrieve a persistent instance if you already know its identifier. 
            One version takes a class object and will load the state into a newly instantiated 
            object. The second version allows you to supply an instance into which the state 
            will be loaded. The form which takes an instance is particularly useful if you plan 
            to use Hibernate with BMP entity beans and is provided for exactly that purpose.
            You may discover other uses. (DIY instance pooling etc.)
        </p><pre class="programlisting">Cat fritz = (Cat) sess.load(Cat.class, generatedId);</pre><pre class="programlisting">// you need to wrap primitive identifiers
long pkId = 1234;
DomesticCat pk = (DomesticCat) sess.load( Cat.class, new Long(pkId) );</pre><pre class="programlisting">Cat cat = new DomesticCat();
// load pk's state into cat
sess.load( cat, new Long(pkId) );
Set kittens = cat.getKittens();</pre><p>

            You may also load an objects using an SQL <tt class="literal">SELECT ... FOR UPDATE</tt>. See the next
            section for a discussion of Hibernate <tt class="literal">LockMode</tt>s.
        </p><pre class="programlisting">Cat cat = (Cat) sess.load(Cat.class, id, LockMode.UPGRADE);</pre><p>
            Note that any associated instances or contained collections are <span class="emphasis"><em>not</em></span> selected 
            <tt class="literal">FOR UPDATE</tt>.
        </p><p>
            It is possible to re-load an object and all its collections at any time, using the 
            <tt class="literal">refresh()</tt> method. This is useful when database triggers are used to
            initialize some of the properties of the object.
        </p><pre class="programlisting">sess.save(cat);
sess.flush(); //force the SQL INSERT
sess.refresh(cat); //re-read the state (after the trigger executes)</pre></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="manipulating-data-s3"></a>7.3.&nbsp;Querying</h2></div></div><div></div></div><p>

            If you don't know the identifier(s) of the object(s) you are looking for, use the <tt class="literal">find()
            </tt> methods of <tt class="literal">Session</tt>. Hibernate supports a simple but powerful object 
            oriented query language.
        </p><pre class="programlisting">List cats = sess.find(
    "from Cat as cat where cat.birthdate = ?",
    date,
    Hibernate.DATE
);

List mates = sess.find(
    "select mate from Cat as cat join cat.mate as mate " +
    "where cat.name = ?",
    name,
    Hibernate.STRING
);

List cats = sess.find( "from Cat as cat where cat.mate.bithdate is null" );

List moreCats = sess.find(
    "from Cat as cat where " + 
    "cat.name = 'Fritz' or cat.id = ? or cat.id = ?",
    new Object[] { id1, id2 },
    new Type[] { Hibernate.LONG, Hibernate.LONG }
);

List mates = sess.find(
    "from Cat as cat where cat.mate = ?",
    izi,
    Hibernate.entity(Cat.class)
);

List problems = sess.find(
    "from GoldFish as fish " +
    "where fish.birthday &gt; fish.deceased or fish.birthday is null"
);</pre><p>
            The second argument to <tt class="literal">find()</tt> accepts an object
            or array of objects. The third argument accepts a Hibernate type or array of
            Hibernate types. These given types are used to bind the given objects to the
            <tt class="literal">?</tt> query placeholders (which map to IN
            parameters of a JDBC <tt class="literal">PreparedStatement</tt>). Just
            as in JDBC, you should use this binding mechanism in preference to string
            manipulation.
        </p><p>

            The <tt class="literal">Hibernate</tt> class defines a number of static methods
            and constants, providing access to most of the built-in types, as instances
            of <tt class="literal">net.sf.hibernate.type.Type</tt>.
        </p><p>
            If you expect your query to return a very large number of objects, but you 
            don't expect to use them all, you might get better performance from the
            <tt class="literal">iterate()</tt> methods, which return a
            <tt class="literal">java.util.Iterator</tt>. The iterator will load objects on 
            demand, using the identifiers returned by an initial SQL query.
        </p><pre class="programlisting">// fetch ids
Iterator iter = sess.iterate("from eg.Qux q order by q.likeliness"); 
while ( iter.hasNext() ) {
    Qux qux = (Qux) iter.next();  // fetch the object
    // something we couldnt express in the query
    if ( qux.calculateComplicatedAlgorithm() ) {
        // delete the current instance
        iter.remove();
        // dont need to process the rest
        break;
    }
}</pre><p>

            Unfortunately <tt class="literal">java.util.Iterator</tt> does not
            declare any exceptions, so any SQL or Hibernate exceptions that occur 
            are wrapped in a <tt class="literal">LazyInitializationException</tt> (a
            subclass of <tt class="literal">RuntimeException</tt>).
        </p><p>
            The <tt class="literal">iterate()</tt> method also performs better if
            you expect that many of the objects are already loaded and cached by 
            the session, or if the query results contain the same objects many
            times. (When no data is cached or repeated, <tt class="literal">find()</tt> 
            is almost always faster.) Heres an example of a query that should be
            called using <tt class="literal">iterate()</tt>:
        </p><pre class="programlisting">

Iterator iter = sess.iterate(
    "select customer, product " + 
    "from Customer customer, " +
    "Product product " +
    "join customer.purchases purchase " +
    "where product = purchase.product"
);</pre><p>
            Calling the previous query using <tt class="literal">find()</tt> would return a very
            large JDBC <tt class="literal">ResultSet</tt> containing the same data many times.
        </p><p>
            Hibernate queries sometimes return tuples of objects, in which case each tuple
            is returned as an array:
        </p><pre class="programlisting">Iterator foosAndBars = sess.iterate(
    "select foo, bar from Foo foo, Bar bar " +
    "where bar.date = foo.date"
);
while ( foosAndBars.hasNext() ) {
    Object[] tuple = (Object[]) foosAndBars.next();
    Foo foo = tuple[0]; Bar bar = tuple[1];
    ....
}</pre><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="manipulating-data-s4"></a>7.3.1.&nbsp;Scalar queries</h3></div></div><div></div></div><p>

            Queries may specify a property of a class in the <tt class="literal">select</tt> clause. 
            They may even call SQL aggregate functions. Properties or aggregates are considered 
            "scalar" results.
        </p><pre class="programlisting">Iterator results = sess.iterate(
        "select cat.color, min(cat.birthdate), count(cat) from Cat cat " +
        "group by cat.color"
);
while ( results.hasNext() ) {
    Object[] row = results.next();
    Color type = (Color) row[0];
    Date oldest = (Date) row[1];
    Integer count = (Integer) row[2];
    .....
}</pre><pre class="programlisting">Iterator iter = sess.iterate(
    "select cat.type, cat.birthdate, cat.name from DomesticCat cat"
);</pre><pre class="programlisting">List list = sess.find(
    "select cat, cat.mate.name from DomesticCat cat"
);</pre></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="manipulating-data-s5"></a>7.3.2.&nbsp;The Query interface</h3></div></div><div></div></div><p>
            If you need to specify bounds upon your result set (the maximum number of rows 
            you want to retrieve and / or the first row you want to retrieve) you should 
            obtain an instance of <tt class="literal">net.sf.hibernate.Query</tt>:
        </p><pre class="programlisting">Query q = sess.createQuery("from DomesticCat cat");
q.setFirstResult(20);
q.setMaxResults(10);
List cats = q.list();</pre><p>

            You may even define a named query in the mapping document. (Remember to use a
            <tt class="literal">CDATA</tt> section if your query contains characters that could
            be interpreted as markup.)
        </p><pre class="programlisting">&lt;query name="eg.DomesticCat.by.name.and.minimum.weight"&gt;&lt;![CDATA[
    from eg.DomesticCat as cat
        where cat.name = ?
        and cat.weight &gt; ?
] ]&gt;&lt;/query&gt;</pre><pre class="programlisting">Query q = sess.getNamedQuery("eg.DomesticCat.by.name.and.minimum.weight");
q.setString(0, name);
q.setInt(1, minWeight);
List cats = q.list();</pre><p>
            The query interface supports the use of named parameters. Named parameters
            are identifiers of the form <tt class="literal">:name</tt> in the query string.
            There are methods on <tt class="literal">Query</tt> for binding values to named
            parameters or JDBC-style <tt class="literal">?</tt> parameters. <span class="emphasis"><em>

            Contrary to JDBC, Hibernate numbers parameters from zero.</em></span> The 
            advantages of named parameters are:
        </p><div class="itemizedlist"><ul type="disc" compact><li><p>
                    named parameters are insensitive to the order they occur in the
                    query string
                </p></li><li><p>
                    they may occur multiple times in the same query
                </p></li><li><p>
                    they are self-documenting
                </p></li></ul></div><pre class="programlisting">//named parameter (preferred)
Query q = sess.createQuery("from DomesticCat cat where cat.name = :name");
q.setString("name", "Fritz");
Iterator cats = q.iterate();</pre><pre class="programlisting">//positional parameter
Query q = sess.createQuery("from DomesticCat cat where cat.name = ?");
q.setString(0, "Izi");
Iterator cats = q.iterate();</pre><pre class="programlisting">//named parameter list
List names = new ArrayList();
names.add("Izi");
names.add("Fritz");
Query q = sess.createQuery("from DomesticCat cat where cat.name in (:namesList)");
q.setParameterList("namesList", names);
List cats = q.list();</pre></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="manipulating-data-s5b"></a>7.3.3.&nbsp;Scrollable iteration</h3></div></div><div></div></div><p>

            If your JDBC driver supports scrollable <tt class="literal">ResultSet</tt>s, the <tt class="literal">Query</tt>
            interface may be used to obtain a <tt class="literal">ScrollableResults</tt> which allows more flexible
            navigation of the query results.
        </p><pre class="programlisting">Query q = sess.createQuery("select cat.name, cat from DomesticCat cat " +
                            "order by cat.name");
ScrollableResults cats = q.scroll();
if ( cats.first() ) {

    // find the first name on each page of an alphabetical list of cats by name
    firstNamesOfPages = new ArrayList();
    do {
        String name = cats.getString(0);
        firstNamesOfPages.add(name);
    }
    while ( cats.scroll(PAGE_SIZE) );

    // Now get the first page of cats
    pageOfCats = new ArrayList();
    cats.beforeFirst();
    int i=0;
    while( ( PAGE_SIZE &gt; i++ ) &amp;&amp; cats.next() ) pageOfCats.add( cats.get(1) );

}</pre><p>

        The behaviour of <tt class="literal">scroll()</tt> is similar to <tt class="literal">iterate()</tt>, except that
        objects may be initialized selectively by <tt class="literal">get(int)</tt>, instead of an entire row being 
        initialized at once.
    </p></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="manipulating-data-s6"></a>7.3.4.&nbsp;Filtering collections</h3></div></div><div></div></div><p>
            A collection <span class="emphasis"><em>filter</em></span> is a special type of query that may be applied to
            a persistent collection or array. The query string may refer to <tt class="literal">this</tt>,
            meaning the current collection element.
        </p><pre class="programlisting">Collection blackKittens = session.filter( 
    pk.getKittens(), "where this.color = ?", Color.BLACK, Hibernate.enum(Color.class)
)</pre><p>

            The returned collection is considered a bag.
        </p><p>
            Observe that filters do not require a <tt class="literal">from</tt> clause (though they may have
            one if required). Filters are not limited to returning the collection elements themselves.
        </p><pre class="programlisting">Collection blackKittenMates = session.filter( 
    pk.getKittens(), "select this.mate where this.color = eg.Color.BLACK"
)</pre></div></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="manipulating-data-s7"></a>7.4.&nbsp;Updating objects saved or loaded in the current session</h2></div></div><div></div></div><p>
            <span class="emphasis"><em>Persistent instances</em></span> (ie. objects loaded, saved, created or
            queried by the <tt class="literal">Session</tt>) may be manipulated by the application 
            and any changes to persistent state will be persisted when the <tt class="literal">Session</tt> 
            is <span class="emphasis"><em>flushed</em></span> (see "flushing" below). So the most straightforward way 
            to update the state of an object is to <tt class="literal">load()</tt> it, and then manipulate 
            it directly. 
        </p><pre class="programlisting">DomesticCat cat = (DomesticCat) sess.load( Cat.class, new Long(69) );
cat.setName("PK");
sess.flush();  // changes to cat are automatically detected and persisted</pre><p>

            Sometimes this programming model is inefficient since it would require both an SQL 
            <tt class="literal">SELECT</tt> (to load an object) and an SQL <tt class="literal">UPDATE</tt> 
            (to persist its updated state) in the same session. Therefore Hibernate offers an 
            alternate approach.
        </p></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="manipulating-data-s8"></a>7.5.&nbsp;Updating objects saved or loaded in a previous session</h2></div></div><div></div></div><p>
            Many applications need to retrieve an object in one transaction, send it to the
            UI layer for manipulation, then save the changes in a new transaction. (Applications 
            that use this kind of approach in a high-concurrency environment usually use versioned 
            data to ensure transaction isolation.) This approach requires a slightly different 
            programming model to the one described in the last section. Hibernate supports this
            model by providing the method <tt class="literal">Session.update()</tt>.
        </p><pre class="programlisting">// in the first session
Cat cat = (Cat) firstSession.load(Cat.class, catId);
Cat potentialMate = new Cat();
firstSession.save(potentialMate);

// in a higher tier of the application
cat.setMate(potentialMate);

// later, in a new session
secondSession.update(cat);  // update cat
secondSession.update(mate); // update mate</pre><p>

            If the <tt class="literal">Cat</tt> with identifier <tt class="literal">catId</tt> had already been loaded 
            by <tt class="literal">secondSession</tt> when the application tried to update it, an exception 
            would have been thrown. 
        </p><p>
            The application should individually <tt class="literal">update()</tt> transient instances 
            reachable from the given transient instance if and <span class="emphasis"><em>only</em></span> if it wants 
            their state also updated. (Except for lifecycle objects.)
        </p><p>

            Hibernate users have requested a general purpose method that either saves a 
            transient instance by generating a new identifier or update the persistent 
            state associated with its current identifier. The <tt class="literal">saveOrUpdate()</tt> 
            method now implements this functionality. Hibernate distinguishes "new" (unsaved) 
            instances from "existing" (saved or loaded in a previous session) instances
            by the value of their identifier property. The <tt class="literal">unsaved-value</tt>
            attribute of the <tt class="literal">&lt;id&gt;</tt> mapping specifies which identifier 
            values should be interpreted as representing a "new" instance.
        </p><pre class="programlisting">&lt;id name="id" type="long" column="uid" unsaved-value="null"&gt;
    &lt;generator class="hilo"/&gt;

&lt;/id&gt;</pre><p>
            The allowed values of <tt class="literal">unsaved-value</tt> are:
        </p><div class="itemizedlist"><ul type="disc" compact><li><p>
                <tt class="literal">any</tt> - always save
                </p></li><li><p>
                <tt class="literal">none</tt> - always update
                </p></li><li><p>

                <tt class="literal">null</tt> - save when identifier is null (this is the default)
                </p></li><li><p>
                valid identifier value - save when identifier is null or the given value
                </p></li></ul></div><pre class="programlisting">// in the first session
Cat cat = (Cat) firstSession.load(Cat.class, catID);

// in a higher tier of the application
Cat mate = new Cat();
cat.setMate(mate);

// later, in a new session
secondSession.saveOrUpdate(cat);   // update existing state (cat has a non-null id)
secondSession.saveOrUpdate(mate);  // save the new instance (mate has a null id)</pre><p>
            The usage and semantics of <tt class="literal">saveOrUpdate()</tt> seems to be confusing
            for new users. Firstly, so long as you are not trying to use instances from one session
            in another new session, you should not need to use <tt class="literal">update()</tt> or
            <tt class="literal">saveOrUpdate()</tt>. Some whole applications will never use either of
            these methods.
        </p><p>

            Usually <tt class="literal">update()</tt> or <tt class="literal">saveOrUpdate()</tt> are used in
            the following scenario:
        </p><div class="itemizedlist"><ul type="disc" compact><li><p>
                    the application loads an object in the first session
                </p></li><li><p>
                    the object is passed up to the UI tier
                </p></li><li><p>
                    some modifications are made to the object
                </p></li><li><p>

                    the object is passed back down to the business logic tier
                </p></li><li><p>
                    the application persists these modifications by calling
                    <tt class="literal">update()</tt> in a second session
                </p></li></ul></div><p>
            <tt class="literal">saveOrUpdate()</tt> does the following:
        </p><div class="itemizedlist"><ul type="disc" compact><li><p>
                    if the object is already persistent in this session, do nothing
                </p></li><li><p>

                    if the object has no identifier property, <tt class="literal">save()</tt> it
                </p></li><li><p>
                    if the object's identifier matches the criteria specified by
                    <tt class="literal">unsaved-value</tt>, <tt class="literal">save()</tt> it
                </p></li><li><p>
                    if another object associated with the session has the same
                    identifier, throw an exception
                </p></li></ul></div></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="manipulating-data-s9"></a>7.6.&nbsp;Deleting persistent objects</h2></div></div><div></div></div><p>

            <tt class="literal">Session.delete()</tt> will remove an object's state from the database. 
            Of course, your application might still hold a reference to it. So it's best to think 
            of <tt class="literal">delete()</tt> as making a persistent instance transient.
        </p><pre class="programlisting">sess.delete(cat);</pre><p>
            You may also delete many objects at once by passing a Hibernate query string to
            <tt class="literal">delete()</tt>.
        </p><p>
            You may now delete objects in any order you like, without risk of foreign key
            constraint violations. Of course, it is still possible to violate a <tt class="literal">NOT
            NULL</tt> constraint on a foreign key column by deleting objects in
            the wrong order.
        </p></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="manipulating-data-s10"></a>7.7.&nbsp;Graphs of objects</h2></div></div><div></div></div><p>

            To save or update all objects in a graph of associated objects, you must either
        </p><div class="itemizedlist"><ul type="disc" compact><li><p>
                    <tt class="literal">save()</tt>, <tt class="literal">saveOrUpdate()</tt> or
                    <tt class="literal">update()</tt> each individual object OR
                </p></li><li><p>
                    map associated objects using <tt class="literal">cascade="all"</tt> or 
                    <tt class="literal">cascade="save-update"</tt>.
                </p></li></ul></div><p>

            Likewise, to delete all objects in a graph, either
        </p><div class="itemizedlist"><ul type="disc" compact><li><p>
                    <tt class="literal">delete()</tt> each individual object OR
                </p></li><li><p>
                    map associated objects using <tt class="literal">cascade="all"</tt>,
                    <tt class="literal">cascade="all-delete-orphan"</tt> or 
                    <tt class="literal">cascade="delete"</tt>.
                </p></li></ul></div><p>

            Recommendation:
        </p><div class="itemizedlist"><ul type="disc" compact><li><p>
                    If the child object's lifespan is bounded by the lifespan of the of the parent 
                    object make it a <span class="emphasis"><em>lifecycle object</em></span> by specifying
                    <tt class="literal">cascade="all"</tt>. 
                </p></li><li><p>
                    Otherwise, <tt class="literal">save()</tt> and <tt class="literal">delete()</tt> it 
                    explicitly from application code. If you really want to save yourself some
                    extra typing, use <tt class="literal">cascade="save-update"</tt> and explicit
                    <tt class="literal">delete()</tt>.
                </p></li></ul></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="manipulating-data-s11a"></a>7.7.1.&nbsp;Lifecycle objects</h3></div></div><div></div></div><p>

            Mapping an association (many-to-one, or collection) with <tt class="literal">cascade="all"</tt> 
            marks the association as a <span class="emphasis"><em>parent / child</em></span> style relationship where 
            save / update / deletion of the parent results in save / update / deletion of the child(ren).
            Futhermore, a mere reference to a child from a persistent parent will result in save / update
            of the child. The metaphor is incomplete, however. A child which becomes unreferenced by its 
            parent is <span class="emphasis"><em>not</em></span> automatically deleted, except in the case of a 
            <tt class="literal">&lt;one-to-many&gt;</tt> association mapped with 
            <tt class="literal">cascade="all-delete-orphan"</tt>. The precise semantics of cascading operations 
            are as follows:
        </p><div class="itemizedlist"><ul type="disc" compact><li><p>

                    If a parent is saved, all children are passed to <tt class="literal">saveOrUpdate()</tt>
                </p></li><li><p>
                    If a parent is passed to <tt class="literal">update()</tt> or <tt class="literal">saveOrUpdate()</tt>, 
                    all children are passed to <tt class="literal">saveOrUpdate()</tt>
                </p></li><li><p>

                    If a transient child becomes referenced by a persistent parent, it is passed to
                    <tt class="literal">saveOrUpdate()</tt>
                </p></li><li><p>
                    If a parent is deleted, all children are passed to <tt class="literal">delete()</tt>
                </p></li><li><p>
                    If a transient child is becomes unreferenced by a persistent parent, <span class="emphasis"><em>nothing 
                    special happens</em></span> (the application should explicitly delete the child if 
                    necessary) unless <tt class="literal">cascade="all-delete-orphan"</tt>, in which case the
                    "orphaned" child is deleted.
                </p></li></ul></div></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="manipulating-data-s11b"></a>7.7.2.&nbsp;Persistence by Reachability</h3></div></div><div></div></div><p>

            Hibernate does not fully implement "persistence by reachability", which would imply
            (inefficient) persistent garbage collection. However, due to popular demand,
            Hibernate does support the notion of entities becoming persistent when referenced
            by another persistent object. Associations marked 
            <tt class="literal">cascade="save-update"</tt> behave in this way. If you wish to use this
            approach throughout your application, its easier to specify the 
            <tt class="literal">default-cascade</tt> attribute of the 
            <tt class="literal">&lt;hibernate-mapping&gt;</tt> element.
        </p></div></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="manipulating-data-s12"></a>7.8.&nbsp;Flushing</h2></div></div><div></div></div><p>
            From time to time the <tt class="literal">Session</tt> will execute the SQL statements 
            needed to synchronize the JDBC connection's state with the state of objects held in 
            memory. This process, <span class="emphasis"><em>flush</em></span>, occurs by default at the following 
            points
        </p><div class="itemizedlist"><ul type="disc" compact><li><p>

                    from some invocations of <tt class="literal">find()</tt> or <tt class="literal">iterate()</tt>
                </p></li><li><p>
                    from <tt class="literal">net.sf.hibernate.Transaction.commit()</tt>
                </p></li><li><p>
                    from <tt class="literal">Session.flush()</tt>

                </p></li></ul></div><p>
            The SQL statements are issued in the following order
        </p><div class="orderedlist"><ol type="1" compact><li><p>
                    all entity insertions, in the same order the corresponding objects
                    were saved using <tt class="literal">Session.save()</tt>
                </p></li><li><p>
                    all entity updates
                </p></li><li><p>
                    all collection deletions
                </p></li><li><p>

                    all collection element deletions, updates and insertions
                </p></li><li><p>
                    all collection insertions
                </p></li><li><p>
                    all entity deletions, in the same order the corresponding objects
                    were deleted using <tt class="literal">Session.delete()</tt>
                </p></li></ol></div><p>
            (An exception is that objects using <tt class="literal">native</tt> ID generation are 
            inserted when they are saved.)
        </p><p>

            Except when you explicity <tt class="literal">flush()</tt>, there are absolutely no 
            guarantees about <span class="emphasis"><em>when</em></span> the <tt class="literal">Session</tt> executes 
            the JDBC calls, only the <span class="emphasis"><em>order</em></span> in which they are executed.
            However, Hibernate does guarantee that the <tt class="literal">Session.find(..)</tt> 
            methods will never return stale data; nor will they return the wrong data.
        </p><p>

            It is possible to change the default behavior so that flush occurs less frequently.
            The <tt class="literal">FlushMode</tt> class defines three different modes. This is most
            useful in the case of "readonly" transactions, where it might be used to achieve a
            (very) slight performance increase.
        </p><pre class="programlisting">sess = sf.openSession();
Transaction tx = sess.beginTransaction();
sess.setFlushMode(FlushMode.COMMIT); //allow queries to return stale state
Cat izi = (Cat) sess.load(Cat.class, id);
izi.setName(iznizi);
// execute some queries....
sess.find("from Cat as cat left outer join cat.kittens kitten"); //change to izi is not flushed!!
....
tx.commit(); //flush occurs</pre></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="manipulating-data-s13"></a>7.9.&nbsp;Ending a Session</h2></div></div><div></div></div><p>
            Ending a session involves four distinct phases:
        </p><div class="itemizedlist"><ul type="disc" compact><li><p>
                    flush the session
                </p></li><li><p>
                    commit the transaction
                </p></li><li><p>

                    close the session
                </p></li><li><p>
                    handle exceptions
                </p></li></ul></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="manipulating-data-s13-1"></a>7.9.1.&nbsp;Flushing the session</h3></div></div><div></div></div><p>
                If you happen to be using the <tt class="literal">Transaction</tt> API, you don't
                need to worry about this step. It will be performed implicitly when the 
                transaction is committed. Otherwise you should call 
                <tt class="literal">Session.flush()</tt> to ensure that all changes are synchronized
                with the database.
            </p></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="manipulating-data-s13-2"></a>7.9.2.&nbsp;Committing the transaction</h3></div></div><div></div></div><p>

                If you are using the Hibernate <tt class="literal">Transaction</tt> API, this looks like:
            </p><pre class="programlisting">tx.commit(); // flush the Session and commit the transaction</pre><p>
                If you are managing JDBC transactions yourself you should manually
                <tt class="literal">commit()</tt> the JDBC connection.
            </p><pre class="programlisting">sess.flush();
sess.connection().commit();  // not necessary for JTA datasource</pre><p>
                If you decide <span class="emphasis"><em>not</em></span> to commit your changes:
            </p><pre class="programlisting">tx.rollback();  // rollback the transaction</pre><p>

                or:
            </p><pre class="programlisting">// not necessary for JTA datasource, important otherwise
sess.connection().rollback();</pre></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="manipulating-data-s13-3"></a>7.9.3.&nbsp;Closing the session</h3></div></div><div></div></div><p>
                A call to <tt class="literal">Session.close()</tt> marks the end of a session. The main implication
                of <tt class="literal">close()</tt> is that the JDBC connection will be relinquished by the session.
            </p><pre class="programlisting">tx.commit();
sess.close();</pre><pre class="programlisting">sess.flush();
sess.connection().commit();  // not necessary for JTA datasource
sess.close();</pre><p>

                If you provided your own connection, <tt class="literal">close()</tt> returns a reference 
                to it, so you can manually close it or return it to the pool. Otherwise <tt class="literal">close()
                </tt> returns it to the pool.
            </p></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="manipulating-data-s13-4"></a>7.9.4.&nbsp;Exception handling</h3></div></div><div></div></div><p>
                If the <tt class="literal">Session</tt> throws an exception (including
                any <tt class="literal">SQLException</tt>), you should immediately
                rollback the transaction, call <tt class="literal">Session.close()</tt>

                and discard the <tt class="literal">Session</tt> instance. Certain
                methods of <tt class="literal">Session</tt> will <span class="emphasis"><em>not</em></span>
                leave the session in a consistent state.
            </p><p>
                The following exception handling idiom is recommended:
            </p><pre class="programlisting">Session sess = factory.openSession();
Transaction tx = null;
try {
    tx = sess.beginTransaction();
    // do some work
    ...
    tx.commit();
}
catch (Exception e) {
    if (tx!=null) tx.rollback();
    throw e;
}
finally {
    sess.close();
}</pre><p>

                Or, when manually managing JDBC transactions:
            </p><pre class="programlisting">Session sess = factory.openSession();
try {
    // do some work
    ...
    sess.flush();
    sess.connection().commit();
}
catch (Exception e) {
    sess.connection().rollback();
    throw e;
}
finally {
    sess.close();
}</pre><p>
                Or, when using a datasource enlisted with JTA:
            </p><pre class="programlisting">UserTransaction ut = .... ;
Session sess = factory.openSession();
try {
    // do some work
    ...
    sess.flush();
}
catch (Exception e) {
    ut.setRollbackOnly();
    throw e;
}
finally {
    sess.close();
}</pre></div></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="manipulating-data-s15"></a>7.10.&nbsp;Interceptors</h2></div></div><div></div></div><p>
            The <tt class="literal">Interceptor</tt> interface provides callbacks from the session to the 
            application allowing the application to inspect and / or manipulate properties of a 
            persistent object before it is saved, updated, deleted or loaded. One 
            possible use for this is to track auditing information. For example, the following 
            <tt class="literal">Interceptor</tt> automatically sets the  <tt class="literal">createTimestamp</tt> 
            when an <tt class="literal">Auditable</tt> is created and updates the 
            <tt class="literal">lastUpdateTimestamp</tt> property when an <tt class="literal">Auditable</tt> is 
            updated.
        </p><pre class="programlisting">package net.sf.hibernate.test;

import java.io.Serializable;
import java.util.Date;
import java.util.Iterator;

import net.sf.hibernate.Interceptor;
import net.sf.hibernate.type.Type;

public class AuditInterceptor implements Interceptor, Serializable {

    private int updates;
    private int creates;

    public void onDelete(Object entity,
                         Serializable id,
                         Object[] state,
                         String[] propertyNames,
                         Type[] types) {
        // do nothing
    }

    public boolean onFlushDirty(Object entity, 
                                Serializable id, 
                                Object[] currentState,
                                Object[] previousState,
                                String[] propertyNames,
                                Type[] types) {

        if ( entity instanceof Auditable ) {
            updates++;
            for ( int i=0; i &lt; propertyNames.length; i++ ) {
                if ( "lastUpdateTimestamp".equals( propertyNames[i] ) ) {
                    currentState[i] = new Date();
                    return true;
                }
            }
        }
        return false;
    }

    public boolean onLoad(Object entity, 
                          Serializable id,
                          Object[] state,
                          String[] propertyNames,
                          Type[] types) {
        return false;
    }

    public boolean onSave(Object entity,
                          Serializable id,
                          Object[] state,
                          String[] propertyNames,
                          Type[] types) {
        
        if ( entity instanceof Auditable ) {
            creates++;
            for ( int i=0; i&lt;propertyNames.length; i++ ) {
                if ( "createTimestamp".equals( propertyNames[i] ) ) {
                    state[i] = new Date();
                    return true;
                }
            }
        }
        return false;
    }

    public void postFlush(Iterator entities) {
        System.out.println("Creations: " + creates + ", Updates: " + updates);
    }

    public void preFlush(Iterator entities) {
        updates=0;
        creates=0;
    }
    
    ......
    ......
    
}</pre><p>

            The interceptor would be specified when a session is created.
        </p><pre class="programlisting">Session session = sf.openSession( new AuditInterceptor() );</pre></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="manipulating-data-s16"></a>7.11.&nbsp;Metadata API</h2></div></div><div></div></div><p>
            Hibernate requires a very rich meta-level model of all entity and value types. From time
            to time, this model is very useful to the application itself. For example, the application
            might use Hibernate's metadata to implement a "smart" deep-copy algorithm that understands
            which objects should be copied (eg. mutable value types) and which should not (eg. 
            immutable value types and, possibly, associated entities).
        </p><p>
            Hibernate exposes metadata via the <tt class="literal">ClassMetadata</tt> and
            <tt class="literal">CollectionMetadata</tt> interfaces and the <tt class="literal">Type</tt>

            hierarchy. Instances of the metadata interfaces may be obtained from the 
            <tt class="literal">SessionFactory</tt>.
        </p><pre class="programlisting">Cat fritz = ......;
Long id = (Long) catMeta.getIdentifier(fritz);
ClassMetadata catMeta = sessionfactory.getClassMetadata(Cat.class);
Object[] propertyValues = catMeta.getPropertyValues(fritz);
String[] propertyNames = catMeta.getPropertyNames();
Type[] propertyTypes = catMeta.getPropertyTypes();
// get a Map of all properties which are not collections or associations
// TODO: what about components?
Map namedValues = new HashMap();
for ( int i=0; i&lt;propertyNames.length; i++ ) {
    if ( !propertyTypes[i].isEntityType() &amp;&amp; !propertyTypes[i].isCollectionType() ) {
        namedValues.put( propertyNames[i], propertyValues[i] );
    }
}</pre></div></div><div class="chapter" lang="en"><div class="titlepage"><div><div><h2 class="title"><a name="parent-child"></a>Chapter&nbsp;8.&nbsp;Parent Child Relationships</h2></div></div><div></div></div><p>
    One of the very first things that new users try to do with Hibernate is to model a parent / child type 
    relationship. There are two different approaches to this. For various reasons the most convenient 
    approach, especially for new users, is to model both <tt class="literal">Parent</tt> and <tt class="literal">Child</tt> 
    as entity classes with a <tt class="literal">&lt;one-to-many&gt;</tt> association from <tt class="literal">Parent</tt> 
    to <tt class="literal">Child</tt>. (The alternative approach is to declare the <tt class="literal">Child</tt> as a 
    <tt class="literal">&lt;composite-element&gt;</tt>.) Now, it turns out that 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 <span class="emphasis"><em>bidirectional one to many 
    association with cascades</em></span> to model a parent / child relationship efficiently and elegantly. Its 
    not at all difficult!
    </p><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="parent-child-collections"></a>8.1.&nbsp;A note about collections</h2></div></div><div></div></div><p>    
        Hibernate collections are considered to be a logical part of their owning entity; never of the 
        contained entities. This is a crucial distinction! It has the following consequences:
    </p><div class="itemizedlist"><ul type="disc"><li><p>

            When we remove / add an object from / to a collection, the version number of the collection owner 
            is incremented.
        </p></li><li><p>
            If an object that was removed from a collection is an instance of a value type (eg, 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.
        </p></li><li><p>
            On the other hand, 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 behaviour 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.
        </p></li></ul></div><p>
        Instead, the default behaviour is that adding an entity to a collection merely creates a link between 
        the two entities, while removing it removes the link. This is very appropriate for all sorts of cases. 
        Where it is not appropriate at all is the case of a parent / child relationship, where the life of the 
        child is bound to the lifecycle of the parent.
    </p></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="parent-child-bidir"></a>8.2.&nbsp;Bidirectional one to many</h2></div></div><div></div></div><p>
        Suppose we start with a simple <tt class="literal">&lt;one-to-many&gt;</tt> association from 
        <tt class="literal">Parent</tt> to <tt class="literal">Child</tt>.
    </p><pre class="programlisting">&lt;set name="children"&gt;

    &lt;key column="parent_id"/&gt;
    &lt;one-to-many class="Child"/&gt;
&lt;/set&gt;</pre><p>
        If we were to execute the following code
    </p><pre class="programlisting">Parent p = .....;
Child c = new Child();
p.getChildren().add(c);
session.save(c);
session.flush();</pre><p>
        Hibernate would issue two SQL statements:
    </p><div class="itemizedlist"><ul type="disc"><li><p>an <tt class="literal">INSERT</tt> to create the record for <tt class="literal">c</tt></p></li><li><p>

            an <tt class="literal">UPDATE</tt> to create the link from <tt class="literal">p</tt> to 
            <tt class="literal">c</tt>
        </p></li></ul></div><p>
        This is not only inefficient, but also violates any <tt class="literal">NOT NULL</tt> constraint on the 
        <tt class="literal">parent_id</tt> column.
    </p><p>

        The underlying cause is that the link (the foreign key <tt class="literal">parent_id</tt>) from 
        <tt class="literal">p</tt> to <tt class="literal">c</tt> is not considered part of the state of the <tt class="literal">Child</tt> 
        object and is therefore not created in the <tt class="literal">INSERT</tt>. So the solution is to make the link part 
        of the <tt class="literal">Child</tt> mapping.
    </p><pre class="programlisting">&lt;many-to-one name="parent" column="parent_id" not-null="true"/&gt;</pre><p>

        (We also need to add the <tt class="literal">parent</tt> property to the <tt class="literal">Child</tt> class.)
    </p><p>
        Now that the <tt class="literal">Child</tt> entity is managing the state of the link, we tell the collection not 
        to update the link. We use the <tt class="literal">inverse</tt> attribute.
    </p><pre class="programlisting">&lt;set name="children" inverse="true"&gt;

    &lt;key column="parent_id"/&gt;
    &lt;one-to-many class="Child"/&gt;
&lt;/set&gt;</pre><p>
        The following code would be used to add a new <tt class="literal">Child</tt>
    </p><pre class="programlisting">Parent p = (Parent) session.load(Parent.class, pid);
Child c = new Child();
c.setParent(p);
p.getChildren().add(c);
session.save(c);
session.flush();</pre><p>
        And now, only one SQL <tt class="literal">INSERT</tt> would be issued!
    </p><p>

        To tighten things up a bit, we could create an <tt class="literal">addChild()</tt> method of 
        <tt class="literal">Parent</tt>.
    </p><pre class="programlisting">public void addChild(Child c) {
    c.setParent(this);
    children.add(c);
}</pre><p>
        Now, the code to add a <tt class="literal">Child</tt> looks like
    </p><pre class="programlisting">Parent p = (Parent) session.load(Parent.class, pid);
Child c = new Child();
p.addChild(c);
session.save(c);
session.flush();</pre></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="parent-child-cascades"></a>8.3.&nbsp;Cascades</h2></div></div><div></div></div><p>

         The explicit call to <tt class="literal">save()</tt> is still annoying. We will address this by 
         using cascades.
     </p><pre class="programlisting">&lt;set name="children" inverse="true" cascade="all"&gt;
    &lt;key column="parent_id"/&gt;
    &lt;one-to-many class="Child"/&gt;
&lt;/set&gt;</pre><p>
         This simplifies the code above to
     </p><pre class="programlisting">Parent p = (Parent) session.load(Parent.class, pid);
Child c = new Child();
p.addChild(c);
session.flush();</pre><p>

         Similarly, we don't need to iterate over the children when saving or deleting a <tt class="literal">Parent</tt>. 
         The following removes <tt class="literal">p</tt> and all its children from the database.
     </p><pre class="programlisting">Parent p = (Parent) session.load(Parent.class, pid);
session.delete(p);
session.flush();</pre><p>
         However, this code
     </p><pre class="programlisting">Parent p = (Parent) session.load(Parent.class, pid);
Child c = (Child) p.getChildren().iterator().next();
p.getChildren().remove(c);
c.setParent(null);
session.flush();</pre><p>
         will not remove <tt class="literal">c</tt> from the database; it will ony remove the link to <tt class="literal">p</tt> 
         (and cause a <tt class="literal">NOT NULL</tt> constraint violation, in this case). You need to explicitly 
         <tt class="literal">delete()</tt> the <tt class="literal">Child</tt> since, by design, Hibernate does not have a 
         garbage collector! Use
     </p><pre class="programlisting">Parent p = (Parent) session.load(Parent.class, pid);
Child c = (Child) p.getChildren().iterator().next();
p.getChildren().remove(c);
session.delete(c);
session.flush();</pre><p>

         Note: even though the collection mapping specifies <tt class="literal">inverse="true"</tt>, cascades are still processed 
         by iterating the collection elements. So if you require that an object be saved, deleted or updated by cascade, 
         you must add it to the collection. It is not enough to simply call <tt class="literal">setParent()</tt>.
     </p><p>
         Now, a <tt class="literal">Child</tt> can't really exist without its parent. So if we remove a <tt class="literal">Child</tt>
         from the collection, we really want it to be deleted. For this, we must use 
         <tt class="literal">cascade="all-delete-orphan"</tt>.
     </p><pre class="programlisting">&lt;set name="children" inverse="true" cascade="all-delete-orphan"&gt;

    &lt;key column="parent_id"/&gt;
    &lt;one-to-many class="Child"/&gt;
&lt;/set&gt;</pre></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="parent-child-update"></a>8.4.&nbsp;Using cascading <tt class="literal">update()</tt></h2></div></div><div></div></div><p>
         Suppose we loaded up a <tt class="literal">Parent</tt> in one <tt class="literal">Session</tt>, made some changes in a UI 
         action and wish to pesist these changes in a new Session (by calling <tt class="literal">update()</tt>). The 
         <tt class="literal">Parent</tt> will contain a collection of childen and, since cascading update is enabled, Hibernate 
         needs to know which children are newly instantiated and which represent existing rows in the database. Lets assume 
         that both <tt class="literal">Parent</tt> and <tt class="literal">Child</tt> have (synthetic) identifier properties of type 
         <tt class="literal">java.lang.Long</tt>. Hibernate will use the identifier property value to determine which of the 
         children are new.
     </p><p>

         The <tt class="literal">unsaved-value</tt> attribute is used to specify the identifier value of a newly instantiated 
         instance. <tt class="literal">unsaved-value</tt> defaults to "null", which is perfect for a <tt class="literal">Long</tt> 
         identifier type. If we would have used a primitive identitifier property, we would need to specify
     </p><pre class="programlisting">&lt;id name="id" type="long" unsaved-value="0"&gt;</pre><p>
         for the <tt class="literal">Child</tt> mapping.
     </p><p>

         The following code will update <tt class="literal">parent</tt> and <tt class="literal">child</tt> and insert 
         <tt class="literal">newChild</tt>.
     </p><pre class="programlisting">//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();</pre><p>
         Well, thats all very well for the case of a generated identifier, but what about assigned identifiers 
         and composite identifiers? This is more difficult, since unsaved-value can't distinguish between a 
         newly instantiated object (with an identifier assigned by the user) and an object loaded in a previous 
         session. In these cases, you will probably need to give Hibernate a hint; either
     </p><div class="itemizedlist"><ul type="disc"><li><p>
             set <tt class="literal">unsaved-value="none"</tt> and explicitly <tt class="literal">save()</tt> 
             newly instantiated children
         </p></li><li><p>

             set <tt class="literal">unsaved-value="any"</tt> and explicitly <tt class="literal">update()</tt> 
             loaded children
         </p></li></ul></div><p>
         before calling <tt class="literal">update(parent)</tt>. The first option is probably more sensible and so that 
         is the default <tt class="literal">unsaved-value</tt> for assigned and composite identifiers.
     </p><p>

         There is one further possibility. There is a new <tt class="literal">Interceptor</tt> method named 
         <tt class="literal">isUnsaved()</tt> which lets the application implement its own strategy for distinguishing 
         newly instantiated objects. For example, you could define a base class for your persistent classes.
     </p><pre class="programlisting">public class Persistent implements Lifecycle {
    private boolean _saved = false;
    public boolean onSave(Session s) {
        _saved=true;
        return NO_VETO;
    }
    public void onLoad(Session s, Serializable id) {
        _saved=true;
    }
    ......
    public boolean isSaved() {
        return _saved;
    }
}</pre><p>
         And implement <tt class="literal">isUnsaved()</tt>
     </p><pre class="programlisting">public Boolean isUnsaved(Object entity) {
    if (entity instanceof Persistent) {
        return new Boolean( !( (Persistent) entity ).isSaved() );
    }
    else {
        return null;
    }
}</pre></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="parent-child-conclusion"></a>8.5.&nbsp;Conclusion</h2></div></div><div></div></div><p>

         There is quite a bit to digest here and it might look confusing first time around. However, in practice, it 
         all works out quite nicely. Most Hibernate applications use the parent / child pattern in many places.
     </p><p>
         We mentioned an alternative in the first paragraph. None of these issues exist in the case of 
         <tt class="literal">&lt;composite-element&gt;</tt> mappings, which have exactly the semantics of a parent / child 
         relationship. Unfortunately there are some severe limitations to composite element classes (at least in the 
         current implementation). Composite elements may not own collections and may not be used in queries. Furthermore, 
         they do not have surrogate primary keys, which is usually a much more flexible relational model.
     </p></div></div><div class="chapter" lang="en"><div class="titlepage"><div><div><h2 class="title"><a name="query-language"></a>Chapter&nbsp;9.&nbsp;Hibernate Query Language</h2></div></div><div></div></div><p>
        Hibernate is equiped with an extremely powerful query language that (quite intentionally)
        looks very much like SQL. But don't be fooled by the syntax; HQL is fully object-oriented,
        understanding notions like inheritence, polymorphism and association.
    </p><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="query-language-s1"></a>9.1.&nbsp;Case Sensitivity</h2></div></div><div></div></div><p>

            Queries are case-insensitive, except for names of Java classes and properties.
            So <tt class="literal">SeLeCT</tt> is the same as
            <tt class="literal">sELEct</tt> is the same as
            <tt class="literal">SELECT</tt> but
            <tt class="literal">net.sf.hibernate.eg.FOO</tt> is not
            <tt class="literal">net.sf.hibernate.eg.Foo</tt> and
            <tt class="literal">foo.barSet</tt> is not
            <tt class="literal">foo.BARSET</tt>.
        </p><p>

            This manual uses lowercase HQL keywords. Some users find queries with uppercase keywords 
            more readable, but we find this convention ugly when embedded in Java code.
        </p></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="query-language-s2"></a>9.2.&nbsp;The from clause</h2></div></div><div></div></div><p>
            The simplest possible Hibernate query is of the form:
        </p><pre class="programlisting">from eg.Cat</pre><p>
            which simply returns all instances of the class <tt class="literal">eg.Cat</tt>. 
        </p><p>
            Most of the time, you will need to assign an <span class="emphasis"><em>alias</em></span>, since
            you will want to refer to the <tt class="literal">Cat</tt> in other parts of the
            query.
        </p><pre class="programlisting">from eg.Cat as cat</pre><p>

            This query assigns the alias <tt class="literal">cat</tt> to <tt class="literal">Cat</tt>
            instances, so we could use that alias later in the query. The <tt class="literal">as</tt>
            keyword is optional; we could also write:
        </p><pre class="programlisting">from eg.Cat cat</pre><p>
            Multiple classes may appear, resulting in a cartesian product or "cross" join.
        </p><pre class="programlisting">from Formula, Parameter</pre><pre class="programlisting">from Formula as form, Parameter as param</pre><p>

            It is considered good practice to name query aliases using an initial lowercase,
            consistent with Java naming standards for local variables
            (eg. <tt class="literal">domesticCat</tt>).
        </p></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="query-language-s3"></a>9.3.&nbsp;Associations and joins</h2></div></div><div></div></div><p>
            We may also define aliases to associated entities using a <tt class="literal">join</tt>.
        </p><pre class="programlisting">from eg.Cat as cat 
    inner join cat.mate as mate
    left outer join cat.kittens as kitten

from eg.Cat as cat left join cat.mate.kittens as kittens

from Formula form full join form.parameter param</pre><p>
            The supported join types are borrowed from ANSI SQL
        </p><div class="itemizedlist"><ul type="disc" compact><li><p>
                    <tt class="literal">inner join</tt>

                </p></li><li><p>
                    <tt class="literal">left outer join</tt>
                </p></li><li><p>
                    <tt class="literal">right outer join</tt>
                </p></li><li><p>
                    <tt class="literal">full join</tt> (not usually useful)
                </p></li></ul></div><p>

            The <tt class="literal">inner join</tt>, <tt class="literal">left outer join</tt> and 
            <tt class="literal">right outer join</tt> constructs may be abbreviated.
        </p><pre class="programlisting">from eg.Cat as cat 
    join cat.mate as mate
    left join cat.kittens as kitten</pre><p>
            In addition, a "fetch" join allows associations to be initialized along with their
            parent objects, using a single select. This is particularly useful in the case of a 
            collection.
        </p><pre class="programlisting">from eg.Cat as cat 
    inner join fetch cat.mate
    left join fetch cat.kittens</pre><p>
            A fetch join does not usually need to assign an alias, because the associated objects 
            should not be used in the <tt class="literal">where</tt> clause (or any other clause). Also, 
            the associated objects are not returned directly in the query results. Instead, they may 
            be accessed via the parent object.
        </p><p>

            Note that, in the current implementation, only one collection role may be fetched
            in a query. Note also that the <tt class="literal">fetch</tt> construct may not be used
            in queries called using <tt class="literal">scroll()</tt> or <tt class="literal">iterate()</tt>.
            Finally, note that <tt class="literal">full join fetch</tt> and <tt class="literal">right join 
            fetch</tt> are not meaningful.
        </p></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="query-language-s4"></a>9.4.&nbsp;The select clause</h2></div></div><div></div></div><p>

            The <tt class="literal">select</tt> clause picks which objects and properties to return in 
            the query result set. Consider:
        </p><pre class="programlisting">select mate 
from eg.Cat as cat 
    inner join cat.mate as mate</pre><p>
            The query will select <tt class="literal">mate</tt>s of other <tt class="literal">Cat</tt>s.
            Actually, you may express this query more compactly as:
        </p><pre class="programlisting">select cat.mate from eg.Cat cat</pre><p>
            You may even select collection elements, using the special <tt class="literal">elements</tt>

            function. The following query returns all kittens of any cat.
        </p><pre class="programlisting">select elements(cat.kittens) from eg.Cat cat</pre><p>
            Queries may return properties of any value type including properties of component type:
        </p><pre class="programlisting">select cat.name from eg.DomesticCat cat
where cat.name like 'fri%'

select cust.name.firstName from Customer as cust</pre><p>
            Queries may return multiple objects and/or properties as an array of type 
            <tt class="literal">Object[]</tt>
        </p><pre class="programlisting">select mother, offspr, mate.name 
from eg.DomesticCat as mother
    inner join mother.mate as mate
    left outer join mother.kittens as offspr</pre><p>
            or as an actual typesafe Java object
        </p><pre class="programlisting">select new Family(mother, mate, offspr)
from eg.DomesticCat as mother
    join mother.mate as mate
    left join mother.kittens as offspr</pre><p>

            assuming that the class <tt class="literal">Family</tt> has an appropriate constructor.
        </p></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="query-language-s4a"></a>9.5.&nbsp;Aggregate functions</h2></div></div><div></div></div><p>
            Queryies may even return aggregate functions of properties.
        </p><pre class="programlisting">select avg(cat.weight), sum(cat.weight), max(cat.weight), count(cat)
from eg.Cat cat</pre><p>
            Collections may also appear inside aggregate functions in the <tt class="literal">select</tt> 
            clause.
        </p><pre class="programlisting">select cat, count( elements(cat.kittens) ) 
from eg.Cat cat group by cat</pre><p>

            The supported aggregate functions are
        </p><div class="itemizedlist"><ul type="disc" compact><li><p>
                    <tt class="literal">avg(...), sum(...), min(...), max(...)</tt>
                </p></li><li><p>
                    <tt class="literal">count(*)</tt>
                </p></li><li><p>
                    <tt class="literal">count(...), count(distinct ...), count(all...)</tt>
                </p></li></ul></div><p>

        The <tt class="literal">distinct</tt> and <tt class="literal">all</tt> keywords may be used and have
        the same semantics as in SQL.
    </p><pre class="programlisting">select distinct cat.name from eg.Cat cat

select count(distinct cat.name), count(cat) from eg.Cat cat</pre></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="query-language-s4b"></a>9.6.&nbsp;polymorphism</h2></div></div><div></div></div><p>
            A query like:
        </p><pre class="programlisting">from eg.Cat as cat</pre><p>
            returns instances not only of <tt class="literal">Cat</tt>, but also of subclasses like
            <tt class="literal">DomesticCat</tt>. Hibernate queries may name <span class="emphasis"><em>any</em></span> Java 
            class or interface in the <tt class="literal">from</tt> clause. The query will return instances 
            of all persistent classes that extend that class or implement the interface. The following 
            query would return all persistent objects:
        </p><pre class="programlisting">from java.lang.Object o</pre><p>

            The interface <tt class="literal">Named</tt> might be implemented by various persistent
            classes:
        </p><pre class="programlisting">from eg.Named n, eg.Named m where n.name = m.name</pre><p>
            Note that these last two queries will require more than one SQL <tt class="literal">SELECT</tt>. This
            means that the <tt class="literal">order by</tt> clause does not correctly order the whole result set.
            (It also means you can't call these queries using <tt class="literal">Query.scroll()</tt>.)
        </p></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="query-language-s5"></a>9.7.&nbsp;The where clause</h2></div></div><div></div></div><p>

            The <tt class="literal">where</tt> clause allows you to narrow the list of instances returned.
        </p><pre class="programlisting">from eg.Cat as cat where cat.name='Fritz'</pre><p>
            returns instances of <tt class="literal">Cat</tt> named 'Fritz'.
        </p><pre class="programlisting">select foo 
from eg.Foo foo, eg.Bar bar
where foo.startDate = bar.date</pre><p>
            will return all instances of <tt class="literal">Foo</tt> for which
            there exists an instance of <tt class="literal">bar</tt> with a
            <tt class="literal">date</tt> property equal to the
            <tt class="literal">startDate</tt> property of the
            <tt class="literal">Foo</tt>. Compound path expressions make the
            <tt class="literal">where</tt> clause extremely powerful. Consider:
        </p><pre class="programlisting">from eg.Cat cat where cat.mate.name is not null</pre><p>

            This query translates to an SQL query with a table (inner) join. If you were to write
            something like
        </p><pre class="programlisting">from eg.Foo foo  
where foo.bar.baz.customer.address.city is not null</pre><p>
            you would end up with a query that would require four table joins in SQL.
        </p><p>
            The <tt class="literal">=</tt> operator may be used to compare not only properties, but also 
            instances:
        </p><pre class="programlisting">from eg.Cat cat, eg.Cat rival where cat.mate = rival.mate

select cat, mate 
from eg.Cat cat, eg.Cat mate
where cat.mate = mate</pre><p>
            The special property (lowercase) <tt class="literal">id</tt> may be used to reference the 
            unique identifier of an object. (You may also use its property name.)
        </p><pre class="programlisting">from eg.Cat as cat where cat.id = 123

from eg.Cat as cat where cat.mate.id = 69</pre><p>

            The second query is efficient. No table join is required!
        </p><p>
            Properties of composite identifiers may also be used. Suppose <tt class="literal">Person</tt> 
            has a composite identifier consisting of <tt class="literal">country</tt> and 
            <tt class="literal">medicareNumber</tt>.
        </p><pre class="programlisting">from bank.Person person
where person.id.country = 'AU' 
    and person.id.medicareNumber = 123456

from bank.Account account
where account.owner.id.country = 'AU' 
    and account.owner.id.medicareNumber = 123456</pre><p>
            Once again, the second query requires no table join.
        </p><p>

            Likewise, the special property <tt class="literal">class</tt> accesses the discriminator value
            of an instance in the case of polymorphic persistence. A Java class name embedded in the 
            where clause will be translated to its discriminator value.
        </p><pre class="programlisting">from eg.Cat cat where cat.class = eg.DomesticCat</pre><p>
            You may also specify properties of components or composite user types (and of components 
            of components, etc). Never try to use a path-expression that ends in a property of component 
            type (as opposed to a property of a component). For example, if <tt class="literal">store.owner</tt>
            is an entity with a component <tt class="literal">address</tt>
        </p><pre class="programlisting">store.owner.address.city    //okay
store.owner.address         //error!</pre><p>

            An "any" type has the special properties <tt class="literal">id</tt> and <tt class="literal">class</tt>,
            allowing us to express a join in the following way (where <tt class="literal">AuditLog.item</tt>
            is a property mapped with <tt class="literal">&lt;any&gt;</tt>).
        </p><pre class="programlisting">from eg.AuditLog log, eg.Payment payment 
where log.item.class = 'eg.Payment' and log.item.id = payment.id</pre><p>
            Notice that <tt class="literal">log.item.class</tt> and <tt class="literal">payment.class</tt>

            would refer to the values of completely different database columns in the above query.
        </p></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="query-language-s6"></a>9.8.&nbsp;Expressions</h2></div></div><div></div></div><p>
            Expressions allowed in the <tt class="literal">where</tt> clause include
            most of the kind of things you could write in SQL:
        </p><div class="itemizedlist"><ul type="disc" compact><li><p>
                    mathematical operators <tt class="literal">+, -, *, /</tt>
                </p></li><li><p>

                    binary comparison operators <tt class="literal">=, &gt;=, &lt;=, &lt;&gt;, !=, like</tt>
                </p></li><li><p>
                    logical operations <tt class="literal">and, or, not</tt>
                </p></li><li><p>
                    string concatenation ||
                </p></li><li><p>

                    SQL scalar functions like <tt class="literal">upper()</tt> and
                    <tt class="literal">lower()</tt>
                </p></li><li><p>
                    Parentheses <tt class="literal">( )</tt> indicate grouping
                </p></li><li><p>
                    <tt class="literal">in</tt>,
                    <tt class="literal">between</tt>,
                    <tt class="literal">is null</tt>

                </p></li><li><p>
                    JDBC IN parameters <tt class="literal">?</tt>
                </p></li><li><p>
                    named parameters <tt class="literal">:name</tt>, <tt class="literal">:start_date</tt>, <tt class="literal">:x1</tt>
                </p></li><li><p>

                    SQL literals <tt class="literal">'foo'</tt>, <tt class="literal">69</tt>, <tt class="literal">'1970-01-01 10:00:01.0'</tt>
                </p></li><li><p>
                    Java <tt class="literal">public static final</tt> constants <tt class="literal">eg.Color.TABBY</tt>

                </p></li></ul></div><p>
            <tt class="literal">in</tt> and <tt class="literal">between</tt> may be used as follows:
        </p><pre class="programlisting">from eg.DomesticCat cat where cat.name between 'A' and 'B'

from eg.DomesticCat cat where cat.name in ( 'Foo', 'Bar', 'Baz' )</pre><p>
            and the negated forms may be written
        </p><pre class="programlisting">from eg.DomesticCat cat where cat.name not between 'A' and 'B'

from eg.DomesticCat cat where cat.name not in ( 'Foo', 'Bar', 'Baz' )</pre><p>
            Likewise, <tt class="literal">is null</tt> and <tt class="literal">is not null</tt> may be used to test 
            for null values.
        </p><p>

            You may test the size of a collection with the special property <tt class="literal">size</tt>, or
            the special <tt class="literal">size()</tt> function.
        </p><pre class="programlisting">from eg.Cat cat where cat.kittens.size &gt; 0

from eg.Cat cat where size(cat.kittens) &gt; 0</pre><p>
            For indexed collections, you may refer to the minimum and maximum indices using
            <tt class="literal">minIndex</tt> and <tt class="literal">maxIndex</tt>. Similarly, you may refer to the
            minimum and maximum elements of a collection of basic type using <tt class="literal">minElement</tt> 
            and <tt class="literal">maxElement</tt>.
        </p><pre class="programlisting">from Calendar cal where cal.holidays.maxElement &gt; current date</pre><p>

            There are also functional forms (which, unlike the constructs above, are not case sensitive):
        </p><pre class="programlisting">from Order order where maxindex(order.items) &gt; 100

from Order order where minelement(order.items) &gt; 10000</pre><p>
            The SQL functions <tt class="literal">any, some, all, exists, in</tt> are supported when passed the element 
            or index set of a collection (<tt class="literal">elements</tt> and <tt class="literal">indices</tt> functions)
            or the result of a subquery (see below).
        </p><pre class="programlisting">select mother from eg.Cat as mother, eg.Cat as kit
where kit in elements(foo.kittens)

select p from eg.NameList list, eg.Person p
where p.name = some elements(list.names)

from eg.Cat cat where exists elements(cat.kittens)

from eg.Player p where 3 &gt; all elements(p.scores)

from eg.Show show where 'fizard' in indices(show.acts)</pre><p>

            Note that these constructs - <tt class="literal">size</tt>, <tt class="literal">elements</tt>,
            <tt class="literal">indices</tt>, <tt class="literal">minIndex</tt>, <tt class="literal">maxIndex</tt>,
            <tt class="literal">minElement</tt>, <tt class="literal">maxElement</tt> - have certain usage 
            restrictions:
        </p><div class="itemizedlist"><ul type="disc" compact><li><p>

                    in a <tt class="literal">where</tt> clause: only for databases with subselects
                </p></li><li><p>
                    in a <tt class="literal">select</tt> clause: only <tt class="literal">elements</tt> and 
                    <tt class="literal">indices</tt> make sense
                </p></li></ul></div><p>

            Elements of indexed collections (arrays, lists, maps) may be referred to by index (in a where clause only)
        </p><pre class="programlisting">from Order order where order.items[0].id = 1234

select person from Person person, Calendar calendar
where calendar.holidays['national day'] = person.birthDay
    and person.nationality.calendar = calendar

select item from Item item, Order order
where order.items[ order.deliveredItemIndices[0] ] = item and order.id = 11

select item from Item item, Order order
where order.items[ maxindex(order.items) ] = item and order.id = 11</pre><p>
            The expression inside <tt class="literal">[]</tt> may even be an arithmetic expression.
        </p><pre class="programlisting">select item from Item item, Order order
where order.items[ size(order.items) - 1 ] = item</pre><p>
            Scalar SQL functions supported by the underlying database may be used
        </p><pre class="programlisting">from eg.DomesticCat cat where upper(cat.name) like 'FRI%'</pre><p>
            If you are not yet convinced by all this, think how much longer and less readable the 
            following query would be in SQL:
        </p><pre class="programlisting">select cust
from Product prod,
    Store store
    inner join store.customers cust
where prod.name = 'widget'
    and store.location.name in ( 'Melbourne', 'Sydney' )
    and prod = all elements(cust.currentOrder.lineItems)</pre><p>

            <span class="emphasis"><em>Hint:</em></span> something like
        </p><pre class="programlisting">SELECT cust.name, cust.address, cust.phone, cust.id, cust.current_order
FROM customers cust,
    stores store,
    locations loc,
    store_customers sc,
    product prod
WHERE prod.name = 'widget'
    AND store.loc_id = loc.id
    AND loc.name IN ( 'Melbourne', 'Sydney' )
    AND sc.store_id = store.id
    AND sc.cust_id = cust.id
    AND prod.id = ALL(
        SELECT item.prod_id
        FROM line_items item, orders o
        WHERE item.order_id = o.id
            AND cust.current_order = o.id
    )</pre></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="query-language-s7"></a>9.9.&nbsp;The order by clause</h2></div></div><div></div></div><p>
            The list returned by a query may be ordered by any property of a returned class or components:
        </p><pre class="programlisting">from eg.DomesticCat cat
order by cat.name asc, cat.weight desc, cat.birthdate</pre><p>
            The optional <tt class="literal">asc</tt> or <tt class="literal">desc</tt> indicate ascending or descending order 
            respectively.
        </p></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="query-language-s8"></a>9.10.&nbsp;The group by clause</h2></div></div><div></div></div><p>

            A query that returns aggregate values may be grouped by any property of a returned class or components:
        </p><pre class="programlisting">select cat.color, sum(cat.weight), count(cat) 
from eg.Cat cat
group by cat.color

select foo.id, avg( elements(foo.names) ), max( indices(foo.names) ) 
from eg.Foo foo
group by foo.id</pre><p>
	        Note: You may use the <tt class="literal">elements</tt> and <tt class="literal">indices</tt> constructs
	        inside a select clause, even on databases with no subselects.
	    </p><p>
	        A <tt class="literal">having</tt> clause is also allowed.
	    </p><pre class="programlisting">select cat.color, sum(cat.weight), count(cat) 
from eg.Cat cat
group by cat.color 
having cat.color in (eg.Color.TABBY, eg.Color.BLACK)</pre><p>

	        SQL functions and aggregate functions are allowed in the <tt class="literal">having</tt> 
	        and <tt class="literal">order by</tt> clauses, if supported by the underlying database (ie. 
	        not in MySQL).
	    </p><pre class="programlisting">select cat
from eg.Cat cat
    join cat.kittens kitten
group by cat
having avg(kitten.weight) &gt; 100
order by count(kitten) asc, sum(kitten.weight) desc</pre><p>
	        Note that neither the <tt class="literal">group by</tt> clause nor the 
	        <tt class="literal">order by</tt> clause may contain arithmetic expressions.
	    </p></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="query-language-s9"></a>9.11.&nbsp;Subqueries</h2></div></div><div></div></div><p>

            For databases that support subselects, Hibernate supports subqueries within queries. A subquery must
            be surrounded by parentheses (often by an SQL aggregate function call). Even correlated subqueries
            (subqueries that refer to an alias in the outer query) are allowed.
        </p><pre class="programlisting">from eg.Cat as fatcat 
where fatcat.weight &gt; ( 
    select avg(cat.weight) from eg.DomesticCat cat 
)

from eg.DomesticCat as cat 
where cat.name = some ( 
    select name.nickName from eg.Name as name 
)
    
from eg.Cat as cat 
where not exists ( 
    from eg.Cat as mate where mate.mate = cat 
)

from eg.DomesticCat as cat 
where cat.name not in ( 
    select name.nickName from eg.Name as name 
)</pre></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="query-language-s10"></a>9.12.&nbsp;Examples</h2></div></div><div></div></div><p>
            Hibernate queries can be quite powerful and complex. In fact, the power of the query language
            is one of Hibernate's main selling points. Here are some example queries very similar to queries
            that I used on a recent project. Note that most queries you will write are much simpler than these!
        </p><p>
            The following query returns the order id, number of items and total value of the order for all 
            unpaid orders for a particular customer and given minimum total value, ordering the results by 
            total value. In determining the prices, it uses the current catalog. The resulting SQL query, 
            against the <tt class="literal">ORDER</tt>, <tt class="literal">ORDER_LINE</tt>, <tt class="literal">PRODUCT</tt>,
            <tt class="literal">CATALOG</tt> and <tt class="literal">PRICE</tt> tables has four inner joins and an
            (uncorrelated) subselect.
        </p><pre class="programlisting">select order.id, sum(price.amount), count(item)
from Order as order
    join order.lineItems as item
    join item.product as product,
    Catalog as catalog
    join catalog.prices as price
where order.paid = false
    and order.customer = :customer
    and price.product = product
    and catalog.effectiveDate &lt; sysdate
    and catalog.effectiveDate &gt;= all (
        select cat.effectiveDate 
        from Catalog as cat
        where cat.effectiveDate &lt; sysdate
    )
group by order
having sum(price.amount) &gt; :minAmount
order by sum(price.amount) desc</pre><p>

            What a monster! Actually, in real life, I'm not very keen on subqueries, so my query was 
            really more like this:
        </p><pre class="programlisting">select order.id, sum(price.amount), count(item)
from Order as order
    join order.lineItems as item
    join item.product as product,
    Catalog as catalog
    join catalog.prices as price
where order.paid = false
    and order.customer = :customer
    and price.product = product
    and catalog = :currentCatalog
group by order
having sum(price.amount) &gt; :minAmount
order by sum(price.amount) desc</pre><p>
            The next query counts the number of payments in each status, excluding all payments in the
            <tt class="literal">AWAITING_APPROVAL</tt> status where the most recent status change was made by the 
            current user. It translates to an SQL query with two inner joins and a correlated subselect 
            against the <tt class="literal">PAYMENT</tt>, <tt class="literal">PAYMENT_STATUS</tt> and 
            <tt class="literal">PAYMENT_STATUS_CHANGE</tt> tables.
        </p><pre class="programlisting">select count(payment), status.name 
from Payment as payment 
    join payment.currentStatus as status
    join payment.statusChanges as statusChange
where payment.status.name &lt;&gt; PaymentStatus.AWAITING_APPROVAL
    or (
        statusChange.timeStamp = ( 
            select max(change.timeStamp) 
            from PaymentStatusChange change 
            where change.payment = payment
        )
        and statusChange.user &lt;&gt; :currentUser
    )
group by status.name, status.sortOrder
order by status.sortOrder</pre><p>

            If I would have mapped the <tt class="literal">statusChanges</tt> collection as a list, instead of a set, 
            the query would have been much simpler to write.
        </p><pre class="programlisting">select count(payment), status.name 
from Payment as payment
    join payment.currentStatus as status
where payment.status.name &lt;&gt; PaymentStatus.AWAITING_APPROVAL
    or payment.statusChanges[ maxIndex(payment.statusChanges) ].user &lt;&gt; :currentUser
group by status.name, status.sortOrder
order by status.sortOrder</pre><p>
            The next query uses the MS SQL Server <tt class="literal">isNull()</tt> function to return all
            the accounts and unpaid payments for the organization to which the current user belongs.
            It translates to an SQL query with three inner joins, an outer join and a subselect against 
            the <tt class="literal">ACCOUNT</tt>, <tt class="literal">PAYMENT</tt>, <tt class="literal">PAYMENT_STATUS</tt>,
            <tt class="literal">ACCOUNT_TYPE</tt>, <tt class="literal">ORGANIZATION</tt> and 
            <tt class="literal">ORG_USER</tt> tables.
        </p><pre class="programlisting">select account, payment
from Account as account
    left outer join account.payments as payment
where :currentUser in elements(account.holder.users)
    and PaymentStatus.UNPAID = isNull(payment.currentStatus.name, PaymentStatus.UNPAID)
order by account.type.sortOrder, account.accountNumber, payment.dueDate</pre><p>

            For some databases, we would need to do away with the (correlated) subselect.
        </p><pre class="programlisting">select account, payment
from Account as account
    join account.holder.users as user
    left outer join account.payments as payment
where :currentUser = user
    and PaymentStatus.UNPAID = isNull(payment.currentStatus.name, PaymentStatus.UNPAID)
order by account.type.sortOrder, account.accountNumber, payment.dueDate</pre></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="query-language-s11"></a>9.13.&nbsp;Tips &amp; Tricks</h2></div></div><div></div></div><p>
            You can count the number of query results without actually returning them:
        </p><pre class="programlisting">( (Integer) session.iterate("select count(*) from ....").next() ).intValue()</pre><p>
            To order a result by the size of a collection, use the following query
            for a one-to-many or many-to-many association:
        </p><pre class="programlisting">select usr
from User as usr 
    left join usr.messages as msg
group by usr
order by count(msg)</pre><p>
            If your database supports subselects, you can place a condition upon selection
            size in the where clause of your query:
        </p><pre class="programlisting">from User usr where size(usr.messages) &gt;= 1</pre><p>

            If your database doesn't support subselects or you're dealing with a one-to-many
            or a many-to-many association, use the following query:
        </p><pre class="programlisting">select usr
from User usr
    join usr.messages msg
group by usr
having count(msg) &gt;= 1</pre><p>
            As this solution can't return a <tt class="literal">User</tt> with zero messages
            because of the inner join, the following form is also useful:
        </p><pre class="programlisting">select usr
from User as usr
    left join usr.messages as msg
group by usr
having count(msg) = 0</pre><p>
            Properties of a JavaBean can be bound to named query parameters:
        </p><pre class="programlisting">Query q = s.createQuery("from foo in class Foo where foo.name=:name and foo.size=:size");
q.setProperties(fooBean); // fooBean has getName() and getSize()
List foos = q.list();</pre><p>
            Collections are pageable by using the <tt class="literal">Query</tt> interface with a filter:
        </p><pre class="programlisting">Query q = s.createFilter( collection, "" ); // the trivial filter
q.setMaxResults(PAGE_SIZE);
q.setFirstResult(PAGE_SIZE * pageNumber);
List page = q.list();</pre><p>

            Collection elements may be ordered or grouped using a query filter:
        </p><pre class="programlisting">List orderedCollection = s.filter( collection, "order by this.amount" );
List counts = s.filter( collection, "select this.type, count(this) group by this.type" );</pre><p>
            You can find the size of a collection without initializing it:
        </p><pre class="programlisting">Integer size = (Integer) s.filter( collection, "select count(*)" ).get(0);</pre></div></div><div class="chapter" lang="en"><div class="titlepage"><div><div><h2 class="title"><a name="worked-example"></a>Chapter&nbsp;10.&nbsp;A Worked Example</h2></div></div><div></div></div><p>
        We'll now demonstrate some of the concepts from the last two sections
        with example code.
    </p><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="worked-example-classes"></a>10.1.&nbsp;Persistent Classes</h2></div></div><div></div></div><p>
            The persistent classes represent a weblog, and an item posted
            in a weblog. They are to be modelled as a standard parent/child
            relationship, but we will use an ordered bag, instead of a set.
        </p><pre class="programlisting">package eg;

import java.util.List;

public class Blog {
    private Long _id;
    private String _name;
    private List _items;

    public Long getId() {
        return _id;
    }
    public List getItems() {
        return _items;
    }
    public String getName() {
        return _name;
    }
    public void setId(Long long1) {
        _id = long1;
    }
    public void setItems(List list) {
        _items = list;
    }
    public void setName(String string) {
        _name = string;
    }
}</pre><pre class="programlisting">package eg;

import java.text.DateFormat;
import java.util.Calendar;

public class BlogItem {
    private Long _id;
    private Calendar _datetime;
    private String _text;
    private String _title;
    private Blog _blog;

    public Blog getBlog() {
        return _blog;
    }
    public Calendar getDatetime() {
        return _datetime;
    }
    public Long getId() {
        return _id;
    }
    public String getText() {
        return _text;
    }
    public String getTitle() {
        return _title;
    }
    public void setBlog(Blog blog) {
        _blog = blog;
    }
    public void setDatetime(Calendar calendar) {
        _datetime = calendar;
    }
    public void setId(Long long1) {
        _id = long1;
    }
    public void setText(String string) {
        _text = string;
    }
    public void setTitle(String string) {
        _title = string;
    }
}</pre></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="worked-example-mappings"></a>10.2.&nbsp;Hibernate Mappings</h2></div></div><div></div></div><p>

            The XML mappings should now be quite straightforward.
        </p><pre class="programlisting">&lt;?xml version="1.0"?&gt;
&lt;!DOCTYPE hibernate-mapping PUBLIC 
        "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"&gt;

&lt;hibernate-mapping&gt;

    &lt;class 
        name="eg.Blog" 
        table="BLOGS" 
        proxy="eg.Blog"&gt;
        
        &lt;id 
            name="id" 
            column="BLOG_ID"&gt;
            
            &lt;generator class="native"/&gt;

            
        &lt;/id&gt;
        
        &lt;property 
            name="name" 
            column="NAME" 
            not-null="true" 
            unique="true"/&gt;
            
        &lt;bag 
            name="items" 
            inverse="true" 
            lazy="true"
            order-by="DATE_TIME" 
            cascade="all"&gt;
            
            &lt;key column="BLOG_ID"/&gt;
            &lt;one-to-many class="eg.BlogItem"/&gt;
            
        &lt;/bag&gt;

        
    &lt;/class&gt;
    
&lt;/hibernate-mapping&gt;</pre><pre class="programlisting">&lt;?xml version="1.0"?&gt;
&lt;!DOCTYPE hibernate-mapping PUBLIC 
        "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"&gt;

&lt;hibernate-mapping&gt;
    
    &lt;class 
        name="eg.BlogItem" 
        table="BLOG_ITEMS" 
        dynamic-update="true"&gt;
        
        &lt;id 
            name="id" 
            column="BLOG_ITEM_ID"&gt;

            
            &lt;generator class="native"/&gt;
            
        &lt;/id&gt;
        
        &lt;property 
            name="title" 
            column="TITLE" 
            not-null="true"/&gt;
            
        &lt;property 
            name="text" 
            column="TEXT" 
            not-null="true"/&gt;
            
        &lt;property 
            name="datetime" 
            column="DATE_TIME" 
            not-null="true"/&gt;
            
        &lt;many-to-one 
            name="blog" 
            column="BLOG_ID" 
            not-null="true"/&gt;

            
    &lt;/class&gt;
    
&lt;/hibernate-mapping&gt;</pre></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="worked-example-code"></a>10.3.&nbsp;Hibernate Code</h2></div></div><div></div></div><p>
            The following class demonstrates some of the kinds of things
            we can do with these classes, using Hibernate.
        </p><pre class="programlisting">package eg;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Query;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.cfg.Configuration;
import net.sf.hibernate.tool.hbm2ddl.SchemaExport;

public class BlogMain {
    
    private SessionFactory _sessions;
    
    public void configure() throws HibernateException {
        _sessions = new Configuration()
            .addClass(Blog.class)
            .addClass(BlogItem.class)
            .buildSessionFactory();
    }
    
    public void exportTables() throws HibernateException {
        Configuration cfg = new Configuration()
            .addClass(Blog.class)
            .addClass(BlogItem.class);
        new SchemaExport(cfg).create(true, true);
    }
    
    public Blog createBlog(String name) throws HibernateException {
        
        Blog blog = new Blog();
        blog.setName(name);
        blog.setItems( new ArrayList() );
        
        Session session = _sessions.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.save(blog);
            tx.commit();
        }
        catch (HibernateException he) {
            if (tx!=null) tx.rollback();
            throw he;
        }
        finally {
            session.close();
        }
        return blog;
    }
    
    public BlogItem createBlogItem(Blog blog, String title, String text) throws HibernateException {
        
        BlogItem item = new BlogItem();
        item.setTitle(title);
        item.setText(text);
        item.setBlog(blog);
        item.setDatetime( Calendar.getInstance() );
        blog.getItems().add(item);
        
        Session session = _sessions.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.update(blog);
            tx.commit();
        }
        catch (HibernateException he) {
            if (tx!=null) tx.rollback();
            throw he;
        }
        finally {
            session.close();
        }
        return item;
    }
    
    public BlogItem createBlogItem(Long blogid, String title, String text) throws HibernateException {
        
        BlogItem item = new BlogItem();
        item.setTitle(title);
        item.setText(text);
        item.setDatetime( Calendar.getInstance() );
        
        Session session = _sessions.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Blog blog = (Blog) session.load(Blog.class, blogid);
            item.setBlog(blog);
            blog.getItems().add(item);
            tx.commit();
        }
        catch (HibernateException he) {
            if (tx!=null) tx.rollback();
            throw he;
        }
        finally {
            session.close();
        }
        return item;
    }
    
    public void updateBlogItem(BlogItem item, String text) throws HibernateException {
        
        item.setText(text);
        
        Session session = _sessions.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.update(item);
            tx.commit();
        }
        catch (HibernateException he) {
            if (tx!=null) tx.rollback();
            throw he;
        }
        finally {
            session.close();
        }
    }
    
    public void updateBlogItem(Long itemid, String text) throws HibernateException {
    
        Session session = _sessions.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            BlogItem item = (BlogItem) session.load(BlogItem.class, itemid);
            item.setText(text);
            tx.commit();
        }
        catch (HibernateException he) {
            if (tx!=null) tx.rollback();
            throw he;
        }
        finally {
            session.close();
        }
    }
    
    public List listAllBlogNamesAndItemCounts(int max) throws HibernateException {
        
        Session session = _sessions.openSession();
        Transaction tx = null;
        List result = null;
        try {
            tx = session.beginTransaction();
            Query q = session.createQuery(
                "select blog.id, blog.name, count(blogItem) " +
                "from Blog as blog " +
                "left outer join blog.items as blogItem " +
                "group by blog.name, blog.id " +
                "order by max(blogItem.datetime)"
            );
            q.setMaxResults(max);
            result = q.list();
            tx.commit();
        }
        catch (HibernateException he) {
            if (tx!=null) tx.rollback();
            throw he;
        }
        finally {
            session.close();
        }
        return result;
    }
    
    public Blog getBlogAndAllItems(Long blogid) throws HibernateException {
        
        Session session = _sessions.openSession();
        Transaction tx = null;
        Blog blog = null;
        try {
            tx = session.beginTransaction();
            Query q = session.createQuery(
                "from Blog as blog " +
                "left outer join fetch blog.items " +
                "where blog.id = :blogid"
            );
            q.setParameter("blogid", blogid);
            blog  = (Blog) q.list().get(0);
            tx.commit();
        }
        catch (HibernateException he) {
            if (tx!=null) tx.rollback();
            throw he;
        }
        finally {
            session.close();
        }
        return blog;
    }
    
    public List listBlogsAndRecentItems() throws HibernateException {
        
        Session session = _sessions.openSession();
        Transaction tx = null;
        List result = null;
        try {
            tx = session.beginTransaction();
            Query q = session.createQuery(
                "from Blog as blog " +
                "inner join blog.items as blogItem " +
                "where blogItem.datetime &gt; :minDate"
            );

            Calendar cal = Calendar.getInstance();
            cal.roll(Calendar.MONTH, false);
            q.setCalendar("minDate", cal);
            
            result = q.list();
            tx.commit();
        }
        catch (HibernateException he) {
            if (tx!=null) tx.rollback();
            throw he;
        }
        finally {
            session.close();
        }
        return result;
    }
}</pre></div></div><div class="chapter" lang="en"><div class="titlepage"><div><div><h2 class="title"><a name="performance"></a>Chapter&nbsp;11.&nbsp;Improving Performance</h2></div></div><div></div></div><p>

        We have already shown how you can use lazy initialization for persistent collections.
        A similar effect is achievable for ordinary object references, using CGLIB proxies.
        We have also mentioned how Hibernate caches persistent objects at the level of a
        <tt class="literal">Session</tt>. More aggressive caching strategies may be configured
        upon a class-by-class basis.
    </p><p>
        In this section, we show you how to use these features, which may be used to
        achieve much higher performance, where necessary.
    </p><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="performance-s4"></a>11.1.&nbsp;Proxies for Lazy Initialization</h2></div></div><div></div></div><p>
            Hibernate implements lazy initializing proxies for persistent objects using runtime
            bytecode enhancement (via the excellent CGLIB library).
        </p><p>
            The mapping file declares a class or interface to use as the proxy interface
            for that class. The recommended approach is to specify the class itself:
        </p><pre class="programlisting">&lt;class name="eg.Order" proxy="eg.Order"&gt;</pre><p>

            The runtime type of the proxies will be a subclass of <tt class="literal">Order</tt>. Note that
            the proxied class must implement a default constructor with at least package visibility.
        </p><p>
            There are some gotchas to be aware of when extending this approach to polymorphic
            classes, eg.
        </p><pre class="programlisting">&lt;class name="eg.Cat" proxy="eg.Cat"&gt;
    ......
    &lt;subclass name="eg.DomesticCat" proxy="eg.DomesticCat"&gt;
        .....
    &lt;/subclass&gt;

&lt;/class&gt;</pre><p>
            Firstly, instances of <tt class="literal">Cat</tt> will never be castable to 
            <tt class="literal">DomesticCat</tt>, even if the underlying instance is an
            instance of <tt class="literal">DomesticCat</tt>.
        </p><pre class="programlisting">Cat cat = (Cat) session.load(Cat.class, id);  // instantiate a proxy (does not hit the db)
if ( cat.isDomesticCat() ) {                  // hit the db to initialize the proxy
    DomesticCat dc = (DomesticCat) cat;       // Error!
    ....
}</pre><p>
            Secondly, it is possible to break proxy <tt class="literal">==</tt>.
        </p><pre class="programlisting">

Cat cat = (Cat) session.load(Cat.class, id);            // instantiate a Cat proxy
DomesticCat dc = 
    (DomesticCat) session.load(DomesticCat.class, id);  // required new DomesticCat proxy!
System.out.println(cat==dc);                            // false</pre><p>
            However, the situation is not quite as bad as it looks. Even though we now have two references
            to different proxy objects, the underlying instance will still be the same object:
        </p><pre class="programlisting">cat.setWeight(11.0);  // hit the db to initialize the proxy
System.out.println( dc.getWeight() );  // 11.0</pre><p>
            Third, you may not use a CGLIB proxy for a <tt class="literal">final</tt> class or a class
            with any <tt class="literal">final</tt> methods.
        </p><p>
            Finally, if your persistent object acquires any resources upon instantiation (eg. in 
            initializers or default constructor), then those resources will also be acquired by
            the proxy. The proxy class is an actual subclass of the persistent class.
        </p><p>

            These problems are all due to fundamental limitations in Java's single inheritence model.
            If you wish to avoid these problems your persistent classes must each implement an interface 
            that declares its business methods. You should specify these interfaces in the mapping file. eg.
        </p><pre class="programlisting">&lt;class name="eg.Cat" proxy="eg.ICat"&gt;
    ......
    &lt;subclass name="eg.DomesticCat" proxy="eg.IDomesticCat"&gt;
        .....
    &lt;/subclass&gt;
&lt;/class&gt;</pre><p>
            where <tt class="literal">Cat</tt> implements the interface <tt class="literal">ICat</tt> and
            <tt class="literal">DomesticCat</tt> implements the interface <tt class="literal">IDomesticCat</tt>. Then 
            proxies for instances of <tt class="literal">Cat</tt> and <tt class="literal">DomesticCat</tt> may be returned 
            by <tt class="literal">load()</tt> or <tt class="literal">iterate()</tt>. (Note that <tt class="literal">find()</tt> 
            does not return proxies.)
        </p><pre class="programlisting">ICat cat = (ICat) session.load(Cat.class, catid);
Iterator iter = session.iterate("from cat in class eg.Cat where cat.name='fritz'");
ICat fritz = (ICat) iter.next();</pre><p>

            Relationships are also lazily initialized. This means you must declare any properties to be of 
            type <tt class="literal">ICat</tt>, not <tt class="literal">Cat</tt>.
        </p><p>
            Certain operations do <span class="emphasis"><em>not</em></span> require proxy initialization
        </p><div class="itemizedlist"><ul type="disc" compact><li><p>
                        <tt class="literal">equals()</tt>, if the persistent class does not override 
                        <tt class="literal">equals()</tt>

                    </p></li><li><p>
                        <tt class="literal">hashCode()</tt>, if the persistent class does not override 
                        <tt class="literal">hashCode()</tt>
                    </p></li><li><p>
                        The identifier getter method
                    </p></li></ul></div><p>
            Hibernate will detect persistent classes that override <tt class="literal">equals()</tt> or
            <tt class="literal">hashCode()</tt>.
        </p><p>

            Exceptions that occur while initializing a proxy are wrapped in a
            <tt class="literal">LazyInitializationException</tt>.
        </p><p>
            Sometimes we need to ensure that a proxy or collection is initialized before closing the
            <tt class="literal">Session</tt>. Of course, we can alway force initialization by calling 
            <tt class="literal">cat.getSex()</tt> or <tt class="literal">cat.getKittens().size()</tt>, for example.
            But that is confusing to readers of the code and is not convenient for generic code.
            The static methods <tt class="literal">Hibernate.initialize()</tt> and <tt class="literal">Hibernate.isInitialized()</tt>

            provide the application with a convenient way of working with lazyily initialized collections or
            proxies. <tt class="literal">Hibernate.initialize(cat)</tt> will force the initialization of a proxy,
            <tt class="literal">cat</tt>, as long as its <tt class="literal">Session</tt> is still open.
            <tt class="literal">Hibernate.initialize( cat.getKittens() )</tt> has a similar effect for the collection
            of kittens. 
        </p></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="performance-s3"></a>11.2.&nbsp;Process Level Cache</h2></div></div><div></div></div><p>
            A Hibernate <tt class="literal">Session</tt> is a transaction-level cache of persistent data. It is
            possible to configure a <tt class="literal">SessionFactory</tt>-level cache on a class-by-class 
            and collection-by-collection basis. Be careful. Caches are never aware of changes made to the
            persistent store by another process (though they may be configured to regularly expire cached 
            data).
        </p><p>

            Hibernate uses Apache Turbine's JCS for factory-level caching. Please see the JCS documentation 
            for information on how to configure data expiry, in-memory caching, disk caching, etc.
        </p><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="performance-s3-1"></a>11.2.1.&nbsp;Mapping</h3></div></div><div></div></div><p>
                The <tt class="literal">&lt;jcs-cache&gt;</tt> element of a class or collection mapping has the
                following form:
            </p><div class="programlistingco"><pre class="programlisting">&lt;jcs-cache usage="read-write|nonstrict-read-write|read-only"<span class="co"><img src="../images/callouts/1.png" alt="(1)"></span> /&gt;</pre><div class="calloutlist"><table border="0" summary="Callout list"><tr><td width="5%" valign="top" align="left"><img src="../images/callouts/1.png" alt="1" border="0"></td><td valign="top" align="left"><p>
                            <tt class="literal">usage</tt> specifies the caching strategy:
                            <tt class="literal">read-write</tt>,
                            <tt class="literal">nonstrict-read-write</tt> or
                            <tt class="literal">read-only</tt>

                        </p></td></tr></table></div></div></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="performance-s3-2"></a>11.2.2.&nbsp;Read Only Cache</h3></div></div><div></div></div><p>
                If your application needs to read but never modify instances of a persistent class, a 
                <tt class="literal">read-only</tt> cache may be used. This is the only style of cache that 
                may be safely used in a cluster or any other environment where Hibernate does not
                have exclusive access to the database.
            </p><pre class="programlisting">&lt;class name="eg.Immutable" mutable="false"&gt;
    ....
    &lt;jcs-cache usage="read-only"/&gt;
&lt;/class&gt;</pre></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="performance-s3-3"></a>11.2.3.&nbsp;Read / Write Cache</h3></div></div><div></div></div><p>

                If the application occasionally needs to update data, a <tt class="literal">read-write</tt>
                cache might be appropriate. This cache should never be used in a clustered environment 
                or where serializable transaction isolation level is needed. If the cache is used in
                a JTA environment, you must specify the property 
                <tt class="literal">hibernate.transaction.manager_lookup_class</tt>, naming a strategy for obtaining 
                the JTA <tt class="literal">TransactionManager</tt>. In other environments, you should ensure
                that the transaction is completed when <tt class="literal">Session.close()</tt> or
                <tt class="literal">Session.disconnect()</tt> is called.
            </p><pre class="programlisting">&lt;class name="eg.Cat" .... &gt;

    &lt;jcs-cache usage="read-write"/&gt;
    ....
    &lt;set name="kittens" ... &gt;
        &lt;jcs-cache usage="read-write"/&gt;
        ....
    &lt;/set&gt;
&lt;/class&gt;</pre></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="performance-s3-4"></a>11.2.4.&nbsp;Nonstrict Read / Write Cache</h3></div></div><div></div></div><p>

                If the application occasionally needs to update data and strict transaction isolation is
                not required, a <tt class="literal">nonstrict-read-write</tt> cache might be appropriate. This cache 
                may be used in a clustered environment when JCS distributed caching is configured. If the 
                cache is used in a JTA environment, you must specify
                <tt class="literal">hibernate.transaction.manager_lookup_class</tt>. In other environments, you should 
                ensure that the transaction is completed when <tt class="literal">Session.close()</tt> or
                <tt class="literal">Session.disconnect()</tt> is called.
            </p></div></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="performance-s5"></a>11.3.&nbsp;Managing the Session Cache</h2></div></div><div></div></div><p>
            Whenever you pass an object to <tt class="literal">save()</tt>, <tt class="literal">update()</tt>

            or <tt class="literal">saveOrUpdate()</tt> and whenever you retrieve an object using 
            <tt class="literal">load()</tt>, <tt class="literal">find()</tt>, <tt class="literal">iterate()</tt>,
            or <tt class="literal">filter()</tt>, that object is added to the internal cache of the
            <tt class="literal">Session</tt>. When <tt class="literal">flush()</tt> is subsequently called,
            the state of that object will be synchronized with the database. If you do not want
            this synchronization to occur or if you are processing a huge number of objects and
            need to manage memory efficiently, the <tt class="literal">evict()</tt> method may be
            used to remove the object and its collections from the cache.
        </p><pre class="programlisting">Iterator cats = sess.iterate("from eg.Cat as cat"); //a huge result set
while ( cats.hasNext() ) {
    Cat cat = (Cat) iter.next();
    doSomethingWithACat(cat);
    sess.evict(cat);
}</pre><p>

            The <tt class="literal">Session</tt> also provides a <tt class="literal">contains()</tt> method
            to determine if an instance belongs to the session cache.
        </p><p>
            For the <tt class="literal">JVM-level</tt> JCS cache, there are methods defined on 
            <tt class="literal">SessionFactory</tt> for evicting the cached state of an instance,
            entire class, collection instance or entire collection role.
        </p></div></div><div class="chapter" lang="en"><div class="titlepage"><div><div><h2 class="title"><a name="collection-performance"></a>Chapter&nbsp;12.&nbsp;Understanding Collection Performance</h2></div></div><div></div></div><p>

        We've already spent quite some time talking about collections.
        In this section we will highlight a couple more issues about
        how collections behave at runtime.
    </p><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="collection-performance-taxonomy"></a>12.1.&nbsp;Taxonomy</h2></div></div><div></div></div><p>Hibernate defines three basic kinds of collections</p><div class="itemizedlist"><ul type="disc"><li><p>collections of values</p></li><li><p>one to many associations</p></li><li><p>many to many associations</p></li></ul></div><p>
            this classification distinguishes the various table and foreign key 
            relationships but does not tell us quite everything we need to know 
            about the relational model. To fully understand the relational structure 
            and performance characteristics, we must also consider the structure of 
            the primary key that is used by Hibernate to update or delete collection 
            rows. This suggests the following classification
        </p><div class="itemizedlist"><ul type="disc"><li><p>indexed collections</p></li><li><p>sets</p></li><li><p>bags</p></li></ul></div><p>
            All indexed collections (maps, lists, arrays) have a primary key consisting 
            of the <tt class="literal">&lt;key&gt;</tt> and <tt class="literal">&lt;index&gt;</tt> 
            columns. In this case collection updates are usually extremely efficient - 
            the primary key may be efficiently indexed and a particular row may be efficiently 
            located when Hibernate tries to update or delete it.
        </p><p>

            Sets have a primary key consisting of <tt class="literal">&lt;key&gt;</tt> and element 
            columns. This may be less efficient for some types of collection element, particularly 
            composite elements or large text or binary fields; the database may not be able to index 
            a complex primary key as efficently.  On the other hand, for one to many or many to many
            associations, particularly in the case of synthetic identifiers, it is likely to be just 
            as efficient. (Side-note: if you want <tt class="literal">SchemaExport</tt> to actually create 
            the primary key of a <tt class="literal">&lt;set&gt;</tt> for you, you must declare all columns 
            as <tt class="literal">not-null="true"</tt>.)
        </p><p>
            Bags are the worst case. Since a bag permits duplicate element values and has no 
            index column, no primary key may be defined. Hibernate has no way of distinguishing 
            between duplicate rows. Hibernate resolves this problem by completely removing 
            (in a single <tt class="literal">DELETE</tt>) and recreating the collection whenever it 
            changes. This might be very inefficient.
        </p><p>

            Note that for a one-to-many association, the "primary key" may not be the physical
            primary key of the database table - but even in this case, the above classification 
            is still useful. (It still reflects how Hibernate "locates" individual rows of the
            collection.)
        </p></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="collection-performance-mostefficient-1"></a>12.2.&nbsp;Lists, maps and sets are the most efficient collections to update</h2></div></div><div></div></div><p>
            From the discussion above, it should be clear that indexed collections 
            and (usually) sets allow the most efficient operation in terms of adding,
            removing and updating elements.
        </p><p>
            There is, arguably, one more advantage that indexed collections have over sets for
            many to many associations or collections of values. Because of the structure of a 
            <tt class="literal">Set</tt>, Hibernate doesn't ever <tt class="literal">UPDATE</tt> a row when 
            an element is "changed". Changes to a <tt class="literal">Set</tt> always work via 
            <tt class="literal">INSERT</tt> and <tt class="literal">DELETE</tt> (of individual rows). Once
            again, this consideration does not apply to one to many associations.
        </p><p>

            After observing that arrays cannot be lazy, we would conclude that lists, maps and sets
            are the most performant collection types. (With the caveat that a set might be less
            efficient for some collections of values.)
        </p><p>
            Sets are expected to be the most common kind of collection in Hibernate applications.
        </p><p>
            <span class="emphasis"><em>There is an undocumented feature in this release of Hibernate. The
            <tt class="literal">&lt;idbag&gt;</tt> mapping implements bag semantics for a collection
            of values or a many to many association and is more efficient that any other
            style of collection in this case!</em></span>
        </p></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="collection-performance-mostefficient-2"></a>12.3.&nbsp;Bags and lists are the most efficient inverse collections</h2></div></div><div></div></div><p>
            Just before you ditch bags forever, there is a particular case in which bags (and also lists) 
            are much more performant than sets. For a collection with <tt class="literal">inverse="true"</tt> 
            (the standard bidirectional one-to-many relationship idiom, for example) we can add elements 
            to a bag or list without needing to initialize (fetch) the bag elements! This is because 
            <tt class="literal">Collection.add()</tt> or <tt class="literal">Collection.addAll()</tt> must always 
            return true for a bag or <tt class="literal">List</tt> (unlike a <tt class="literal">Set</tt>). This can 
            make the following common code much faster.
        </p><pre class="programlisting">Parent p = (Parent) sess.load(Parent.class, id);
Child c = new Child();
c.setParent(p);
p.getChildren().add(c);  //no need to fetch the collection!
sess.flush();</pre></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="collection-performance-oneshotdelete"></a>12.4.&nbsp;One shot delete</h2></div></div><div></div></div><p>

            Occasionally, deleting collection elements one by one can be extremely inefficient. Hibernate 
            isn't completly stupid, so it knows not to do that in the case of an newly-empty collection 
            (if you called <tt class="literal">list.clear()</tt>, for example). In this case, Hibernate will 
            issue a single <tt class="literal">DELETE</tt> and we are done!
        </p><p>
            Suppose we add a single element to a collection of size twenty and then remove two elements. 
            Hibernate will issue one <tt class="literal">INSERT</tt> statement and two <tt class="literal">DELETE</tt> 
            statements (unless the collection is a bag). This is certainly desirable.
        </p><p>

            However, suppose that we remove eighteen elements, leaving two and then add thee new elements. 
            There are two possible ways to proceed
        </p><div class="itemizedlist"><ul type="disc"><li><p>delete eighteen rows one by one and then insert three rows</p></li><li><p>remove the whole collection (in one SQL <tt class="literal">DELETE</tt>) and insert 
            all five current elements (one by one)</p></li></ul></div><p>
            Hibernate isn't smart enough to know that the second option is probably quicker in this case. 
            (And it would probably be undesirable for Hibernate to be that smart; such behaviour might 
            confuse database triggers, etc.)
        </p><p>
            Fortunately, you can force this behaviour (ie. the second strategy) at any time by discarding 
            (ie. dereferencing) the original collection and returning a newly instantiated collection with 
            all the current elements. This can be very useful and powerful from time to time.
        </p></div></div><div class="chapter" lang="en"><div class="titlepage"><div><div><h2 class="title"><a name="query-criteria"></a>Chapter&nbsp;13.&nbsp;Criteria Queries</h2></div></div><div></div></div><p>
        Hibernate now features an experimental criteria query API. For now, this API
        is much less powerful and than the more mature HQL query facilities.
    </p><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="query-criteria-s1"></a>13.1.&nbsp;Creating a <tt class="literal">Criteria</tt> instance</h2></div></div><div></div></div><p>

        The interface <tt class="literal">net.sf.hibernate.Criteria</tt> represents a query against
        a particular persistent class. The <tt class="literal">Session</tt> is a factory for 
        <tt class="literal">Criteria</tt> instances.
    </p><pre class="programlisting">Criteria crit = sess.createCriteria(Cat.class);
crit.setMaxResults(50);
List cats = crit.list();</pre></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="query-criteria-s2"></a>13.2.&nbsp;Narrowing the result set</h2></div></div><div></div></div><p>
        A particular query criterion is an instance of the abstract class
        <tt class="literal">net.sf.hibernate.expression.Expression</tt>. This class
        defines factory methods for obtaining certain built-in 
        <tt class="literal">Expressions</tt> but is also intended for extension by
        Hibernate applications.
    </p><pre class="programlisting">List cats = sess.createCriteria(Cat.class)
    .add( Expression.like("name", "Fritz%") )
    .add( Expression.between("weight", minWeight, maxWeight) )
    .list();</pre><p>

        Expressions may be grouped logically.
    </p><pre class="programlisting">List cats = sess.createCriteria(Cat.class)
    .add( Expression.like("name", "Fritz%") )
    .add( Expression.or(
    	Expression.eq( "age", new Integer(0) ),
    	Expression.isNull("age")
    ) )
    .list();</pre><pre class="programlisting">List cats = sess.createCriteria(Cat.class)
    .add( Expression.in( "name", new String[] { "Fritz", "Izi", "Pk" } ) )
    .add( Expression.disjunction()
        .add( Expression.isNull("age") )
    	.add( Expression.eq("age", new Integer(0) ) )
    	.add( Expression.eq("age", new Integer(1) ) )
    	.add( Expression.eq("age", new Integer(2) ) )
    ) )
    .list();</pre><p>
        There are quite a range of built-in criterion types (<tt class="literal">Expression</tt>
        sublcasses), but one that is especially useful lets you specify SQL directly.
    </p><pre class="programlisting">List cats = sess.createCriteria(Cat.class)
    .add( Expression.sql("lower($alias.name) like lower(?)", "Fritz%", Hibernate.STRING) )
    .list();</pre><p>
        The <tt class="literal">$alias</tt> placeholder with be replaced by the row alias
        of the queried entity.
    </p></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="query-criteria-s3"></a>13.3.&nbsp;Ordering the results</h2></div></div><div></div></div><p>

        You may order the results using <tt class="literal">net.sf.hibernate.expression.Order</tt>.
    </p><pre class="programlisting">List cats = sess.createCriteria(Cat.class)
    .add( Expression.like("name", "F%")
    .addOrder( Order.asc("name") )
    .addOrder( Order.desc("age") )
    .setMaxResults(50)
    .list();</pre></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="query-criteria-s4"></a>13.4.&nbsp;Dynamic association fetching</h2></div></div><div></div></div><p>
        You may specify association fetching semantics at runtime using
        <tt class="literal">setFetchMode()</tt>.
    </p><pre class="programlisting">List cats = sess.createCriteria(Cat.class)
    .add( Expression.like("name", "Fritz%") )
    .setFetchMode("mate", FetchMode.EAGER)
    .list();</pre></div></div><div class="chapter" lang="en"><div class="titlepage"><div><div><h2 class="title"><a name="transactions"></a>Chapter&nbsp;14.&nbsp;Transactions And Concurrency</h2></div></div><div></div></div><p>

        Hibernate is not itself a database. It is a lightweight object-relational
        mapping tool. Transaction management is delegated to the underlying database
        connection. If the connection is enlisted with JTA, operations performed by the
        <tt class="literal">Session</tt> are atomically part of the wider JTA
        transaction. Hibernate can be seen as a thin adapter to JDBC, adding object
        oriented semantics.
    </p><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="transactions-s1"></a>14.1.&nbsp;Configurations, Sessions and Factories</h2></div></div><div></div></div><p>
            A <tt class="literal">SessionFactory</tt> is an expensive-to-create, threadsafe object 
            intended to be shared by all application threads. A <tt class="literal">Session</tt> 
            is an inexpensive, nonthreadsafe object that should be used once, for a single 
            business process, and then discarded. For example, when using Hibernate in a 
            servlet-based application, servlets could obtain a <tt class="literal">SessionFactory</tt> 
            using
        </p><pre class="programlisting">SessionFactory sf = (SessionFactory)getServletContext().getAttribute("my.session.factory");</pre><p>

            Each call to a service method could create a new <tt class="literal">Session</tt>,
            <tt class="literal">flush()</tt> it, <tt class="literal">commit()</tt> its connection,
            <tt class="literal">close()</tt> it and finally discard it.
        </p><p>
            In a stateless session bean, a similar approach could be used. The bean would
            obtain a <tt class="literal">SessionFactory</tt> in <tt class="literal">setSessionContext()</tt>. 
            Then each business method would create a <tt class="literal">Session</tt>,
            <tt class="literal">flush()</tt> it and <tt class="literal">close()</tt> it. Of course, the 
            application should not <tt class="literal">commit()</tt> the connection. (Leave that to 
            JTA.)
        </p><p>

            Ensure you understand the semantics of <tt class="literal">flush()</tt>.
            Flushing synchronizes the persistent store with in-memory changes but
            <span class="emphasis"><em>not</em></span> vice-versa. So when you <tt class="literal">flush()</tt>
            and then <tt class="literal">commit()</tt> the connection, the session will
            continue to contain potentially stale data. The <span class="emphasis"><em>only</em></span> way you
            may continue to use a session after a <tt class="literal">flush()</tt> and
            <tt class="literal">commit()</tt> is by using versioned data. 
        </p><p>

            The next few sections will discuss alternative approaches that utilize versioning
            to ensure transaction atomicity. These are considered "advanced" approaches to be used 
            with care.
        </p></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="transactions-s2"></a>14.2.&nbsp;Threads and connections</h2></div></div><div></div></div><p>
            You should observe the following practices when creating Hibernate Sessions:
        </p><div class="itemizedlist"><ul type="disc" compact><li><p>
                    Never create more than one concurrent <tt class="literal">Session</tt> or
                    <tt class="literal">Transaction</tt> instance per database connection
                </p></li><li><p>

                    Be extremely careful when creating more than one <tt class="literal">Session</tt>
                    per datastore per transaction. The <tt class="literal">Session</tt> itself keeps
                    track of updates made to loaded objects, so a different <tt class="literal">Session</tt>
                    might see stale data.
                </p></li><li><p>
                    The <tt class="literal">Session</tt> is <span class="emphasis"><em>not</em></span> threadsafe. We can't see
                    why you would need to share a session between two concurrent threads but if you
                    must, make sure your threads carefully synchronize on the
                    <tt class="literal">Session</tt> object before accessing it.
                </p></li></ul></div></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="transactions-s3"></a>14.3.&nbsp;Optimistic Locking / Versioning</h2></div></div><div></div></div><p>

            Many business processes require a whole series of interactions with the user
            interleaved with database accesses. In web and enterprise applications it is
            not acceptable for a database transaction to span a user interaction.
            Maintaining isolation of business processes becomes the partial responsibility
            of the application tier. The only approach that is consistent with high
            concurrency and high scalability is optimistic locking with versioning.
            Hibernate provides for three possible approaches to writing application code
            that uses optimistic locking.
        </p><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="transactions-s3-1"></a>14.3.1.&nbsp;Long session with automatic versioning</h3></div></div><div></div></div><p>
                A single <tt class="literal">Session</tt> instance and its persistent instances are 
                used for the whole business process. The <tt class="literal">Session</tt> uses 
                optimistic locking with versioning to ensure that many database transactions 
                appear to the application as a single logical transaction. The 
                <tt class="literal">Session</tt> is disconnected when waiting for user interaction. 
                This approach is the most efficient in terms of database access. The application 
                need not concern itself with version checking or with reassociating transient 
                instances.
            </p><pre class="programlisting">// foo is an instance loaded earlier by the Session
session.reconnect();
foo.setProperty("bar");
session.flush();
session.connection().commit();
session.disconnect();</pre></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="transactions-s3-2"></a>14.3.2.&nbsp;Many sessions with automatic versioning</h3></div></div><div></div></div><p>

                Each interaction with the persistent store occurs in a new <tt class="literal">Session</tt>. 
                However, the same persistent instances are reused for each interaction with the database. 
                The application manipulates the state of transient instances originally loaded in another
                <tt class="literal">Session</tt> and then "reassociates" them using 
                <tt class="literal">Session.update()</tt> or <tt class="literal">Session.saveOrUpdate()</tt>.
            </p><pre class="programlisting">// foo is an instance loaded by a previous Session
foo.setProperty("bar");
session = factory.openSession();
session.saveOrUpdate(foo);
session.flush();
session.connection().commit();
session.close();</pre></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="transactions-s3-3"></a>14.3.3.&nbsp;Application version checking</h3></div></div><div></div></div><p>
                Each interaction with the persistent store occurs in a new <tt class="literal">Session</tt> 
                that reloads all persistent instances from the datastore before manipulating them. 
                This approach forces the application to carry out its own version checking to ensure 
                business process isolation. (Of course, Hibernate will still <span class="emphasis"><em>update</em></span>

                version numbers for you.) This approach is the least efficient in terms of database access. 
                It is the approach most similar to entity EJBs.
            </p><pre class="programlisting">// foo is an instance loaded by a previous Session
session = factory.openSession();
int oldVersion = foo.getVersion();
session.load( foo, foo.getKey() );
if ( oldVersion!=foo.getVersion ) throw new StaleObjectStateException();
foo.setProperty("bar");
session.flush();
session.connection().commit();
session.close();</pre><p>
                Of course, if you are operating in a low-data-concurrency environment and don't
                require version checking, you may use this approach and just skip the version
                check.
            </p></div></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="transactions-s4"></a>14.4.&nbsp;Session disconnection</h2></div></div><div></div></div><p>
            The first approach described above is to maintain a single <tt class="literal">Session</tt> 
            for a whole business process thats spans user think time. (For example, a servlet might 
            keep a <tt class="literal">Session</tt> in the user's <tt class="literal">HttpSession</tt>.) For 
            performance reasons you should
        </p><div class="orderedlist"><ol type="1" compact><li><p>

                    commit the <tt class="literal">Transaction</tt> (or JDBC connection) and then
                </p></li><li><p>
                    disconnect the <tt class="literal">Session</tt> from the JDBC connection
                </p></li></ol></div><p>
            before waiting for user activity. The method <tt class="literal">Session.disconnect()</tt> 
            will disconnect the session from the JDBC connection and return the connection to 
            the pool (unless you provided the connection).
        </p><p>

            <tt class="literal">Session.reconnect()</tt> obtains a new connection (or you may supply one) 
            and restarts the session. After reconnection, to force a version check on data you aren't 
            updating, you may call <tt class="literal">Session.lock()</tt> on any objects that might have
            been updated by another transaction. You don't need to lock any data that you
            <span class="emphasis"><em>are</em></span> updating.
        </p><p>
            Heres an example:
        </p><pre class="programlisting">SessionFactory sessions;
List fooList;
Bar bar;
....
Session s = sessions.openSession();

Transaction tx = null;
try {
    tx = s.beginTransaction();

    fooList = s.find(
    	"select foo from eg.Foo foo where foo.Date = current date"
        // uses db2 date function
    );
    bar = (Bar) s.create(Bar.class);

    tx.commit();
}
catch (Exception e) {
    if (tx!=null) tx.rollback();
    s.close();
    throw e;
}
s.disconnect();</pre><p>
            Later on:
        </p><pre class="programlisting">s.reconnect();

try {
    tx = sessions.beginTransaction();

    bar.setFooTable( new HashMap() );
    Iterator iter = fooList.iterator();
    while ( iter.hasNext() ) {
        Foo foo = (Foo) iter.next();
        s.lock(foo, LockMode.READ);    //check that foo isn't stale
        bar.getFooTable().put( foo.getName(), foo );
    }

    tx.commit();
}
catch (Exception e) {
    if (tx!=null) tx.rollback();
    throw e;
}
finally {
    s.close();
}</pre><p>

            You can see from this how the relationship between <tt class="literal">Transaction</tt>s and
            <tt class="literal">Session</tt>s is many-to-one, A <tt class="literal">Session</tt> represents a 
            conversation between the application and the persistent store. The
            <tt class="literal">Transaction</tt> breaks that conversation up into atomic units of work.
        </p></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="transactions-s5"></a>14.5.&nbsp;Pessimistic Locking</h2></div></div><div></div></div><p>
            It is not intended that users spend much time worring about locking strategies. Its usually
            enough to specify an isolation level and then simply let the database do all the work.
            However, advanced users may sometimes wish to obtain pessimistic locks, or re-obtain locks 
            at the start of a new transaction.
        </p><p>

            The <tt class="literal">LockMode</tt> class defines the different lock levels that may be acquired
            by Hibernate. A lock is obtained by the following mechanisms:
        </p><div class="itemizedlist"><ul type="disc" compact><li><p>
                    <tt class="literal">LockMode.WRITE</tt> is acquired automatically when Hibernate updates or inserts 
                    a row. 
                </p></li><li><p>
                    <tt class="literal">LockMode.UPGRADE</tt> may be acquired upon explicit user request using 
                    <tt class="literal">SELECT ... FOR UPDATE</tt> on databases which support that syntax.
                </p></li><li><p>

                    <tt class="literal">LockMode.UPGRADE_NOWAIT</tt> may be acquired upon explicit user request using a 
                    <tt class="literal">SELECT ... FOR UPDATE NOWAIT</tt> under Oracle.
                </p></li><li><p>
                    <tt class="literal">LockMode.READ</tt> is acquired automatically when Hibernate reads data
                    under Repeatable Read or Serializable isolation level. May be re-acquired by explicit user 
                    request.
                </p></li><li><p>
            <tt class="literal">LockMode.NONE</tt> represents the absence of a lock. All objects switch to this
            lock mode at the end of a <tt class="literal">Transaction</tt>. Objects associated with the session 
            via a call to <tt class="literal">update()</tt> or <tt class="literal">saveOrUpdate()</tt> also start out 
            in this lock mode.
        </p></li></ul></div><p>

            The "explicit user request" is expressed in one of the following ways:
        </p><div class="itemizedlist"><ul type="disc" compact><li><p>
                    A call to <tt class="literal">Session.load()</tt>, specifying a <tt class="literal">LockMode</tt>.
                </p></li><li><p>
                    A call to <tt class="literal">Session.lock()</tt>.
                </p></li><li><p>
                    A call to <tt class="literal">Query.setLockMode()</tt>.
                </p></li></ul></div><p>

            If <tt class="literal">Session.load()</tt> is called with <tt class="literal">UPGRADE</tt> or
            <tt class="literal">UPGRADE_NOWAIT</tt>, and the requested object was not yet loaded by
            the session, the object is loaded using <tt class="literal">SELECT ... FOR UPDATE</tt>.
            If <tt class="literal">load()</tt> is called for an object that is already loaded with
            a less restrictive lock than the one requested, Hibernate calls 
            <tt class="literal">lock()</tt> for that object.
        </p><p>

            <tt class="literal">Session.lock()</tt> performs a version number check if the specified lock
            mode is <tt class="literal">READ</tt>, <tt class="literal">UPGRADE</tt> or 
            <tt class="literal">UPGRADE_NOWAIT</tt>. (In the case of <tt class="literal">UPGRADE</tt> or
            <tt class="literal">UPGRADE_NOWAIT</tt>, <tt class="literal">SELECT ... FOR UPDATE</tt> is used.)
        </p><p>

            If the database does not support the requested lock mode, Hibernate will use an appropriate
            alternate mode (instead of throwing an exception). This ensures that applications will
            be portable.
        </p></div></div><div class="chapter" lang="en"><div class="titlepage"><div><div><h2 class="title"><a name="examples"></a>Chapter&nbsp;15.&nbsp;Mapping Examples</h2></div></div><div></div></div><p>
        This section shows off some more complex association mappings.
    </p><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="examples-s0"></a>15.1.&nbsp;Employer/Employee</h2></div></div><div></div></div><p>
            The following model of the relationship between <tt class="literal">Employer</tt> and 
            <tt class="literal">Employee</tt> uses an actual entity class (<tt class="literal">Employment</tt>) 
            to represent the association. This is done because there might be more than one
            period of employment for the same two parties. Components are used to model monetory 
            values and employee names.
        </p><div class="mediaobject" align="center"><img src="../images/EmployerEmployee.gif" align="middle"></div><p>

            Heres a possible mapping document:
        </p><pre class="programlisting">&lt;hibernate-mapping&gt;
        
    &lt;class name="Employer" table="employers"&gt;
        &lt;id name="id"&gt;
            &lt;generator class="sequence"&gt;
                &lt;param name="sequence"&gt;employer_id_seq&lt;/param&gt;

            &lt;/generator&gt;
        &lt;/id&gt;
        &lt;property name="name"/&gt;
    &lt;/class&gt;

    &lt;class name="Employment" table="employment_periods"&gt;

        &lt;id name="id"&gt;
            &lt;generator class="sequence"&gt;
                &lt;param name="sequence"&gt;employment_id_seq&lt;/param&gt;
            &lt;/generator&gt;
        &lt;/id&gt;

        &lt;property name="startDate" column="start_date"/&gt;
        &lt;property name="endDate" column="end_date"/&gt;

        &lt;component name="hourlyRate" class="MonetoryAmount"&gt;
            &lt;property name="amount"&gt;
                &lt;column name="hourly_rate" sql-type="NUMERIC(12, 2)"/&gt;
            &lt;/property&gt;

            &lt;property name="currency" length="12"/&gt;
        &lt;/component&gt;

        &lt;many-to-one name="employer" column="employer_id" not-null="true"/&gt;
        &lt;many-to-one name="employee" column="employee_id" not-null="true"/&gt;

    &lt;/class&gt;

    &lt;class name="Employee" table="employees"&gt;
        &lt;id name="id"&gt;
            &lt;generator class="sequence"&gt;
                &lt;param name="sequence"&gt;employee_id_seq&lt;/param&gt;
            &lt;/generator&gt;

        &lt;/id&gt;
        &lt;property name="taxfileNumber"/&gt;
        &lt;component name="name" class="Name"&gt;
            &lt;property name="firstName"/&gt;
            &lt;property name="initial"/&gt;
            &lt;property name="lastName"/&gt;

        &lt;/component&gt;
    &lt;/class&gt;

&lt;/hibernate-mapping&gt;</pre><p>
        And heres the table schema generated by <tt class="literal">SchemaExport</tt>.
    </p><pre class="programlisting">create table employers (
    id BIGINT not null, 
    name VARCHAR(255), 
    primary key (id)
)

create table employment_periods (
    id BIGINT not null,
    hourly_rate NUMERIC(12, 2),
    currency VARCHAR(12), 
    employee_id BIGINT not null, 
    employer_id BIGINT not null, 
    end_date TIMESTAMP, 
    start_date TIMESTAMP, 
    primary key (id)
)

create table employees (
    id BIGINT not null, 
    firstName VARCHAR(255), 
    initial CHAR(1), 
    lastName VARCHAR(255), 
    taxfileNumber VARCHAR(255), 
    primary key (id)
)

alter table employment_periods 
    add constraint employment_periodsFK0 foreign key (employer_id) references employers
alter table employment_periods 
    add constraint employment_periodsFK1 foreign key (employee_id) references employees
create sequence employee_id_seq
create sequence employment_id_seq
create sequence employer_id_seq</pre></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="examples-s1"></a>15.2.&nbsp;Author/Work</h2></div></div><div></div></div><p>

            Consider the following model of the relationships between <tt class="literal">Work</tt>,
            <tt class="literal">Author</tt> and <tt class="literal">Person</tt>. We represent the relationship
            between <tt class="literal">Work</tt> and <tt class="literal">Author</tt> as a many-to-many
            association. We choose to represent the relationship between <tt class="literal">Author</tt> 
            and <tt class="literal">Person</tt> as one-to-one association. Another possibility would be to 
            have <tt class="literal">Author</tt> extend <tt class="literal">Person</tt>.  
        </p><div class="mediaobject" align="center"><img src="../images/AuthorWork.gif" align="middle"></div><p>

            The following mapping document correctly represents these relationships:
        </p><pre class="programlisting">&lt;hibernate-mapping&gt;

    &lt;class name="Work" table="works" discriminator-value="W"&gt;

        &lt;id name="id" column="id"&gt;
            &lt;generator class="native"/&gt;
        &lt;/id&gt;

        &lt;discriminator column="type" type="character"/&gt;

        &lt;property name="title"/&gt;
        &lt;set name="authors" table="author_work" lazy="true"&gt;
            &lt;key&gt;
                &lt;column name="work_id" not-null="true"/&gt;
            &lt;/key&gt;

            &lt;many-to-many class="Author"&gt;
                &lt;column name="author_id" not-null="true"/&gt;
            &lt;/many-to-many&gt;
        &lt;/set&gt;

        &lt;subclass name="Book" discriminator-value="B"&gt;
            &lt;property name="text"/&gt;

        &lt;/subclass&gt;

        &lt;subclass name="Song" discriminator-value="S"&gt;
            &lt;property name="tempo"/&gt;
            &lt;property name="genre"/&gt;
        &lt;/subclass&gt;

    &lt;/class&gt;

    &lt;class name="Author" table="authors"&gt;

        &lt;id name="id" column="id"&gt;
            &lt;!-- The Author must have the same identifier as the Person --&gt;
            &lt;generator class="assigned"/&gt; 
        &lt;/id&gt;

        &lt;property name="alias"/&gt;
        &lt;one-to-one name="person" constrained="true"/&gt;

        &lt;set name="works" table="author_work" inverse="true" lazy="true"&gt;
            &lt;key column="author_id"/&gt;
            &lt;many-to-many class="Work" column="work_id"/&gt;

        &lt;/set&gt;

    &lt;/class&gt;

    &lt;class name="Person" table="persons"&gt;
        &lt;id name="id" column="id"&gt;
            &lt;generator class="native"/&gt;

        &lt;/id&gt;
        &lt;property name="name"/&gt;
    &lt;/class&gt;

&lt;/hibernate-mapping&gt;</pre><p>
        There are four tables in this mapping. <tt class="literal">works</tt>, 
        <tt class="literal">authors</tt> and <tt class="literal">persons</tt> hold work, author
        and person data respectively. <tt class="literal">author_work</tt> is an association
        table linking authors to works. Heres the table schema, as generated by
        <tt class="literal">SchemaExport</tt>.
    </p><pre class="programlisting">create table works (
    id BIGINT not null generated by default as identity, 
    tempo FLOAT, 
    genre VARCHAR(255), 
    text INTEGER, 
    title VARCHAR(255), 
    type CHAR(1) not null, 
    primary key (id)
)

create table author_work (
    author_id BIGINT not null, 
    work_id BIGINT not null, 
    primary key (work_id, author_id)
)

create table authors (
    id BIGINT not null generated by default as identity, 
    alias VARCHAR(255), 
    primary key (id)
)

create table persons (
    id BIGINT not null generated by default as identity, 
    name VARCHAR(255), 
    primary key (id)
)

alter table authors 
    add constraint authorsFK0 foreign key (id) references persons
alter table author_work 
    add constraint author_workFK0 foreign key (author_id) references authors
alter table author_work
    add constraint author_workFK1 foreign key (work_id) references works</pre></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="examples-s2"></a>15.3.&nbsp;Customer/Order/Product</h2></div></div><div></div></div><p>

            Now consider a model of the relationships between <tt class="literal">Customer</tt>,
            <tt class="literal">Order</tt> and <tt class="literal">LineItem</tt> and <tt class="literal">Product</tt>.
            There is a one-to-many association between <tt class="literal">Customer</tt> and
            <tt class="literal">Order</tt>, but how should we represent <tt class="literal">Order</tt> / 
            <tt class="literal">LineItem</tt> / <tt class="literal">Product</tt>? I've chosen to map
            <tt class="literal">LineItem</tt> as an association class representing the many-to-many
            association between <tt class="literal">Order</tt> and <tt class="literal">Product</tt>. In
            Hibernate, this is called a composite element.
        </p><div class="mediaobject" align="center"><img src="../images/CustomerOrderProduct.gif" align="middle"></div><p>

            The mapping document:
        </p><pre class="programlisting">&lt;hibernate-mapping&gt;

    &lt;class name="Customer" table="customers"&gt;
        &lt;id name="id"&gt;
            &lt;generator class="native"/&gt;
        &lt;/id&gt;

        &lt;property name="name"/&gt;
        &lt;set name="orders" inverse="true" lazy="true"&gt;
            &lt;key column="customer_id"/&gt;
            &lt;one-to-many class="Order"/&gt;
        &lt;/set&gt;
    &lt;/class&gt;

    &lt;class name="Order" table="orders"&gt;
        &lt;id name="id"&gt;
            &lt;generator class="native"/&gt;
        &lt;/id&gt;
        &lt;property name="date"/&gt;
        &lt;many-to-one name="customer" column="customer_id"/&gt;

        &lt;list name="lineItems" table="line_items" lazy="true"&gt;
            &lt;key column="order_id"/&gt;
            &lt;index column="line_number"/&gt;
            &lt;composite-element class="LineItem"&gt;
                &lt;property name="quantity"/&gt;
                &lt;many-to-one name="product" column="product_id"/&gt;

            &lt;/composite-element&gt;
        &lt;/list&gt;
    &lt;/class&gt;

    &lt;class name="Product" table="products"&gt;
        &lt;id name="id"&gt;
            &lt;generator class="native"/&gt;

        &lt;/id&gt;
        &lt;property name="serialNumber"/&gt;
    &lt;/class&gt;

&lt;/hibernate-mapping&gt;</pre><p>
        <tt class="literal">customers</tt>, <tt class="literal">orders</tt>, <tt class="literal">line_items</tt> and 
        <tt class="literal">products</tt> hold customer, order, order line item and product data
        respectively. <tt class="literal">line_items</tt> also acts as an association table linking
        orders with products.
    </p><pre class="programlisting">create table customers (
    id BIGINT not null generated by default as identity, 
    name VARCHAR(255), 
    primary key (id)
)

create table orders (
    id BIGINT not null generated by default as identity, 
    customer_id BIGINT, 
    date TIMESTAMP, 
    primary key (id)
)

create table line_items (
    line_number INTEGER not null, 
    order_id BIGINT not null, 
    product_id BIGINT, 
    quantity INTEGER, 
    primary key (order_id, line_number)
)

create table products (
    id BIGINT not null generated by default as identity, 
    serialNumber VARCHAR(255), 
    primary key (id)
)

alter table orders 
    add constraint ordersFK0 foreign key (customer_id) references customers
alter table line_items
    add constraint line_itemsFK0 foreign key (product_id) references products
alter table line_items
    add constraint line_itemsFK1 foreign key (order_id) references orders</pre></div></div><div class="chapter" lang="en"><div class="titlepage"><div><div><h2 class="title"><a name="best-practices"></a>Chapter&nbsp;16.&nbsp;Best Practices</h2></div></div><div></div></div><div class="variablelist"><dl><dt><span class="term">Write fine-grained classes and map them using <tt class="literal">&lt;component&gt;</tt>.</span></dt><dd><p>

                    Use an <tt class="literal">Address</tt> class to encapsulate <tt class="literal">street</tt>,
                    <tt class="literal">suburb</tt>, <tt class="literal">state</tt>, <tt class="literal">postcode</tt>.
                    This encourages code reuse and simplifies refactoring.
                </p></dd><dt><span class="term">Declare identifier properties on persistent classes.</span></dt><dd><p>
                    Hibernate makes identifier properties optional. There are all sorts of reasons why
                    you should use them. We recommend that identifiers be 'synthetic' (generated, with
                    no business meaning) and of a non-primitive type. For maximum flexibility, use
                    <tt class="literal">java.lang.Long</tt> or <tt class="literal">java.lang.String</tt>.
                </p></dd><dt><span class="term">Place each class mapping in its own file.</span></dt><dd><p>

                     Don't use a single monolithic mapping document. Map <tt class="literal">com.eg.Foo</tt> in 
                     the file <tt class="literal">com/eg/Foo.hbm.xml</tt>. This makes particularly good sense in 
                     a team environment.
                </p></dd><dt><span class="term">Load mappings as resources.</span></dt><dd><p>
                    Deploy the mappings along with the classes they map.
                </p></dd><dt><span class="term">Consider externalising query strings.</span></dt><dd><p>
                    This is a good practice if your queries call non-ANSI-standard SQL functions. 
                    Externalising the query strings will make the application more portable.
                </p></dd><dt><span class="term">Use bind variables.</span></dt><dd><p>

                     As in JDBC, always replace non-constant values by "?". Never use string manipulation to 
                     bind a non-constant value in a query! Even better, consider using named parameters in
                     queries.
                </p></dd><dt><span class="term">Don't manage your own JDBC connections.</span></dt><dd><p>
                    Hibernate lets the application manage JDBC connections. This approach should be considered 
                    a last-resort. If you can't use the built-in connections providers, consider providing your 
                    own implementation of <tt class="literal">net.sf.hibernate.connection.ConnectionProvider</tt>.
                </p></dd><dt><span class="term">Consider using a custom type.</span></dt><dd><p>
                    Suppose you have a Java type, say from some library, that needs to be persisted but doesn't 
                    provide the accessors needed to map it as a component. You should consider implementing
                    <tt class="literal">net.sf.hibernate.UserType</tt>. This approach frees the application
                    code from implementing transformations to / from a Hibernate type.
                </p></dd><dt><span class="term">Use hand-coded JDBC in bottlenecks.</span></dt><dd><p>
                    In performance-critical areas of the system, some kinds of operations (eg. mass update /
                    delete) might benefit from direct JDBC. But please, wait until you <span class="emphasis"><em>know</em></span> 
                    something is a bottleneck. And don't assume that direct JDBC is necessarily faster. If need to 
                    use direct JDBC, it might be worth opening a Hibernate <tt class="literal">Session</tt> and using that SQL 
                    connection. That way you can still use the same transaction strategy and underlying connection 
                    provider.
                </p></dd><dt><span class="term">Understand <tt class="literal">Session</tt> flushing.</span></dt><dd><p>

                    From time to time the Session synchronizes its persistent state with the database. Performance will
                    be affected if this process occurs too often. You may sometimes minimize unnecessary flushing by 
                    disabling automatic flushing or even by changing the order of queries and other operations within a 
                    particular transaction.      
                </p></dd><dt><span class="term">In a three tiered architecture, consider using <tt class="literal">saveOrUpdate()</tt>.</span></dt><dd><p>
                    When using a servlet / session bean architecture, you could pass persistent objects loaded in
                    the session bean to and from the servlet / JSP layer. Use a new session to service each request. 
                    Use <tt class="literal">Session.update()</tt> or <tt class="literal">Session.saveOrUpdate()</tt> to update the 
                    persistent state of an object.
                </p></dd><dt><span class="term">In a two tiered architecture, consider using session disconnection.</span></dt><dd><p>
                    When using a servlet only, you may reuse the same session for multiple client requests. Just
                    remember to disconnect the session before returning control to the client.
                </p></dd><dt><span class="term">Don't treat exceptions as recoverable.</span></dt><dd><p>

                    This is more of a necessary paractice than a "best" practice. When an exception occurs, roll back 
                    the <tt class="literal">Transaction</tt> and close the <tt class="literal">Session</tt>. If you don't, Hibernate
                    can't guarantee that in-memory state accurately represents persistent state. As a special case of this,
                    do not use <tt class="literal">Session.load()</tt> to determine if an instance with the given identifier 
                    exists on the database; use <tt class="literal">find()</tt> instead.
                </p></dd><dt><span class="term">Prefer lazy fetching for associations.</span></dt><dd><p>
                    Use eager (outer-join) fetching sparingly. Use proxies and/or lazy collections for most associations
                    to classes that are not cached at the JVM-level. For associations to cached classes, where there is
                    a high probability of a cache hit, explicitly disable eager fetching using 
                    <tt class="literal">outer-join="false"</tt>. When an outer-join fetch is appropriate to a particular use
                    case, use a query with a <tt class="literal">left join</tt>.
                </p></dd><dt><span class="term">Consider abstracting your business logic from Hibernate.</span></dt><dd><p>

                    Hide (Hibernate) data-access code behind an interface. Combine the <span class="emphasis"><em>DAO</em></span> and 
                    <span class="emphasis"><em>Thread Local Session</em></span> patterns. You can even have some classes persisted by
                    handcoded JDBC, associated to Hibernate via a <tt class="literal">UserType</tt>. (This advice is 
                    intended for "sufficiently large" applications; it is not appropriate for an application with
                    five tables!)
                </p></dd></dl></div></div><div class="chapter" lang="en"><div class="titlepage"><div><div><h2 class="title"><a name="toolsetguide"></a>Chapter&nbsp;17.&nbsp;Toolset Guide</h2></div></div><div></div></div><p>
        Roundtrip engineering with Hibernate is possible using a set of commandline tools 
        maintained as part of the Hibernate project, along with Hibernate support built into
        XDoclet, Middlegen and AndroMDA.
    </p><p>

        The Hibernate main package comes bundled with the most important tool (it can even
        be used from "inside" Hibernate on-the-fly):
    </p><div class="itemizedlist"><ul type="disc"><li><p>
            DDL schema generation from a mapping file
            (aka <tt class="literal">SchemaExport</tt>, <tt class="literal">hbm2ddl</tt>)
        </p></li></ul></div><p>
        Other tools directly provided by the Hibernate project are delivered with a separate
        package, <span class="emphasis"><em>Hibernate Extensions</em></span>. This package includes tools for
        the following tasks:
    </p><div class="itemizedlist"><ul type="disc"><li><p>
            Java source generation from a mapping file (aka <tt class="literal">CodeGenerator</tt>,
            <tt class="literal">hbm2java</tt>)
        </p></li><li><p>

            mapping file generation from compiled Java classes or from
            Java source with XDoclet markup (aka <tt class="literal">MapGenerator</tt>,
            <tt class="literal">class2hbm</tt>)
        </p></li></ul></div><p>
        There's actually another utitily living in Hibernate Extensions: <tt class="literal">ddl2hbm</tt>.
        It is considered deprecated and will no longer be maintained, Middlegen does a better job
        for the same task.
    </p><p>
        Third party tools with Hibernate support are:
    </p><div class="itemizedlist"><ul type="disc"><li><p>
            Middlegen (mapping file generation from an existing database schema)
        </p></li><li><p>

            AndroMDA (MDA (Model-Driven Architecture) approach generating code for
            persistent classes from UML diagrams and their XML/XMI representation)
        </p></li></ul></div><p>
        These 3rd party tools are not documented in this reference. Please refer to the Hibernate
        website for up-to-date information (a snapshot of the site is included in the Hibernate
        main package).
    </p><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="toolsetguide-s1"></a>17.1.&nbsp;Schema Generation</h2></div></div><div></div></div><p>
            DDL may be generated from your mapping files by a command line utility. A batch file
            is located in the <tt class="literal">hibernate-x.x.x/bin</tt> directory of the core
            Hibernate package.
        </p><p>
            The generated schema include referential integrity constraints (primary and foreign keys) for entity
            and collection tables. Tables and sequences are also created for mapped identifier generators.
        </p><p>

            You <span class="emphasis"><em>must</em></span> specify a SQL <tt class="literal">Dialect</tt> via the 
            <tt class="literal">hibernate.dialect</tt> property when using this tool.
        </p><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="toolsetguide-s1-2"></a>17.1.1.&nbsp;Customizing the schema</h3></div></div><div></div></div><p>
                Many Hibernate mapping elements define an optional attribute named <tt class="literal">length</tt>. You may set 
                the length of a column with this attribute.
            </p><p>

                Some tags also accept a <tt class="literal">not-null</tt> attribute (for generating a <tt class="literal">NOT NULL</tt>
                constraint on table columns) and a <tt class="literal">unique</tt> attribute (for generating <tt class="literal">UNIQUE</tt>
                constraint on table columns).
            </p><p>

                Some tags accept an <tt class="literal">index</tt> attribute for specifying the name of an index for that
                column and a <tt class="literal">unique-key</tt> attribute for specifying the name of a multi-column unique
                key.
            </p><p>
                Examples:
            </p><pre class="programlisting">&lt;property name="foo" type="string" length="64" not-null="true"/&gt;

&lt;subcollection column="serial_numbers" role="serial-numbers" not-null="true" unique="true"/&gt;

&lt;element column="serial_number" type="long" not-null="true" unique="true"/&gt;</pre><p>
                Alternatively, these elements also accept a child <tt class="literal">&lt;column&gt;</tt> element. This is
                particularly useful for multi-column types:
            </p><pre class="programlisting">&lt;property name="foo" type="string"&gt;
    &lt;column name="foo" length="64" not-null="true" sql-type="text"/&gt;
&lt;/property&gt;

&lt;subcollection role="serial-numbers"/&gt;

    &lt;column name="serial_numbers" not-null="true" unique="true"/&gt;
&lt;/subcollection&gt;

&lt;property name="bar" type="my.customtypes.MultiColumnType"/&gt;
    &lt;column name="fee" not-null="true" index="bar_idx"/&gt;
    &lt;column name="fi" not-null="true" index="bar_idx"/&gt;
    &lt;column name="fo" not-null="true" index="bar_idx"/&gt;

&lt;/property&gt;</pre><p>
                The <tt class="literal">sql-type</tt> attribute allows the user to override the default mapping
                of Hibernate type to SQL datatype.
            </p><div class="table"><a name="d0e7622"></a><p class="title"><b>Table&nbsp;17.1.&nbsp;Summary</b></p><table summary="Summary" border="1"><colgroup><col><col></colgroup><thead><tr><th>Attribute</th><th>Values</th><th>Interpretation</th></tr></thead><tbody><tr><td><tt class="literal">length</tt></td><td><tt class="literal">true|false</tt></td><td>column length</td></tr><tr><td><tt class="literal">not-null</tt></td><td><tt class="literal">true|false</tt></td><td>specfies that the column should be non-nullable</td></tr><tr><td><tt class="literal">unique</tt></td><td><tt class="literal">true|false</tt></td><td>specifies that the column should have a unique constraint</td></tr><tr><td><tt class="literal">index</tt></td><td><tt class="literal">index_name</tt></td><td>specifies the name of a (multi-column) index</td></tr><tr><td><tt class="literal">unique-key</tt></td><td><tt class="literal">unique_key_name</tt></td><td>specifies the name of a multi-column unique constraint</td></tr><tr><td><tt class="literal">sql-type</tt></td><td><tt class="literal">column_type</tt></td><td>

                                overrides the default column type (attribute of 
                                <tt class="literal">&lt;column&gt;</tt> element only)
                            </td></tr></tbody></table></div></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="toolsetguide-s1-3"></a>17.1.2.&nbsp;Running the tool</h3></div></div><div></div></div><p>
                The <tt class="literal">SchemaExport</tt> tool writes a DDL script to standard out and/or
                executes the DDL statements.
            </p><p>
                <tt class="literal">java -cp </tt><span class="emphasis"><em>hibernate_classpaths</em></span>

                <tt class="literal">net.sf.hibernate.tool.hbm2ddl.SchemaExport</tt> <span class="emphasis"><em>options mapping_files</em></span>
            </p><div class="table"><a name="d0e7715"></a><p class="title"><b>Table&nbsp;17.2.&nbsp;<tt class="literal">SchemaExport</tt> Command Line Options</b></p><table summary="SchemaExport Command Line Options" border="1"><colgroup><col><col></colgroup><thead><tr><th>Option</th><th>Description</th></tr></thead><tbody><tr><td><tt class="literal">--quiet</tt></td><td>don't output the script to stdout</td></tr><tr><td><tt class="literal">--drop</tt></td><td>only drop the tables</td></tr><tr><td><tt class="literal">--text</tt></td><td>don't export to the database</td></tr><tr><td><tt class="literal">--output=my_schema.ddl</tt></td><td>output the ddl script to a file</td></tr><tr><td><tt class="literal">--properties=hibernate.properties</tt></td><td>read database properties from a file</td></tr><tr><td><tt class="literal">--format</tt></td><td>format the generated SQL nicely in the script</td></tr><tr><td><tt class="literal">--delimiter=x</tt></td><td>set an end of line delimiter for the script</td></tr></tbody></table></div><p>

                You may even embed <tt class="literal">SchemaExport</tt> in your application:
            </p><pre class="programlisting">Configuration cfg = ....;
new SchemaExport(cfg).create(false, true);</pre></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="toolsetguide-s1-4"></a>17.1.3.&nbsp;Properties</h3></div></div><div></div></div><p>
                Database properties may be specified
            </p><div class="itemizedlist"><ul type="disc" compact><li><p>as system properties with <tt class="literal">-D</tt><span class="emphasis"><em>&lt;property&gt;</em></span></p></li><li><p>in <tt class="literal">hibernate.properties</tt></p></li><li><p>in a named properties file with <tt class="literal">--properties</tt></p></li></ul></div><p>

                The needed properties are:
            </p><div class="table"><a name="d0e7804"></a><p class="title"><b>Table&nbsp;17.3.&nbsp;SchemaExport Connection Properties</b></p><table summary="SchemaExport Connection Properties" border="1"><colgroup><col><col></colgroup><thead><tr><th>Property Name</th><th>Description</th></tr></thead><tbody><tr><td><tt class="literal">hibernate.connection.driver</tt></td><td>jdbc driver class</td></tr><tr><td><tt class="literal">hibernate.connection.url</tt></td><td>jdbc url</td></tr><tr><td><tt class="literal">hibernate.connection.username</tt></td><td>database user</td></tr><tr><td><tt class="literal">hibernate.connection.password</tt></td><td>user password</td></tr><tr><td><tt class="literal">hibernate.dialect</tt></td><td>dialect</td></tr></tbody></table></div></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="toolsetguide-s1-5"></a>17.1.4.&nbsp;Using Ant</h3></div></div><div></div></div><p>

                You can call <tt class="literal">SchemaExport</tt> from your Ant build script:
            </p><pre class="programlisting">&lt;target name="schemaexport"&gt;
    &lt;taskdef name="schemaexport"
        classname="net.sf.hibernate.tool.hbm2ddl.SchemaExportTask"
        classpathref="class.path"/&gt;
    
    &lt;schemaexport
        properties="hibernate.properties"
        quiet="no"
        text="no"
        drop="no"
        delimiter=";"
        output="schema-export.sql"&gt;
        &lt;fileset dir="src"&gt;
            &lt;include name="**/*.hbm.xml"/&gt;

        &lt;/fileset&gt;
    &lt;/schemaexport&gt;
&lt;/target&gt;</pre></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="toolsetguide-s1-6"></a>17.1.5.&nbsp;Incremental schema updates</h3></div></div><div></div></div><p>
                The <tt class="literal">SchemaUpdate</tt> tool will update an existing schema with "incremental" changes.
                Note that <tt class="literal">SchemaUpdate</tt> depends heavily upon the JDBC metadata API, so it will
                not work with all JDBC drivers.
            </p><p>

                <tt class="literal">java -cp </tt><span class="emphasis"><em>hibernate_classpaths</em></span>
                <tt class="literal">net.sf.hibernate.tool.hbm2ddl.SchemaUpdate</tt> <span class="emphasis"><em>options mapping_files</em></span>
            </p><div class="table"><a name="d0e7881"></a><p class="title"><b>Table&nbsp;17.4.&nbsp;<tt class="literal">SchemaUpdate</tt> Command Line Options</b></p><table summary="SchemaUpdate Command Line Options" border="1"><colgroup><col><col></colgroup><thead><tr><th>Option</th><th>Description</th></tr></thead><tbody><tr><td><tt class="literal">--quiet</tt></td><td>don't output the script to stdout</td></tr><tr><td><tt class="literal">--properties=hibernate.properties</tt></td><td>read database properties from a file</td></tr></tbody></table></div><p>

                You may embed <tt class="literal">SchemaUpdate</tt> in your application:
            </p><pre class="programlisting">Configuration cfg = ....;
new SchemaUpdate(cfg).execute(false);</pre></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="toolsetguide-s1-7"></a>17.1.6.&nbsp;Using Ant for incremental schema updates</h3></div></div><div></div></div><p>
                You can call <tt class="literal">SchemaUpdate</tt> from the Ant script:
            </p><pre class="programlisting">&lt;target name="schemaupdate"&gt;
    &lt;taskdef name="schemaupdate"
        classname="net.sf.hibernate.tool.hbm2ddl.SchemaUpdateTask"
        classpathref="class.path"/&gt;

    
    &lt;schemaupdate
        properties="hibernate.properties"
        quiet="no"&gt;
        &lt;fileset dir="src"&gt;
            &lt;include name="**/*.hbm.xml"/&gt;
        &lt;/fileset&gt;
    &lt;/schemaupdate&gt;
&lt;/target&gt;</pre></div></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="toolsetguide-s2"></a>17.2.&nbsp;Code Generation</h2></div></div><div></div></div><p>

            The Hibernate code generator may be used to generate skeletal Java implementation classes
            from a Hibernate mapping file. This tool is included in the Hibernate Extensions package
            (a seperate download).
        </p><p>
            <tt class="literal">hbm2java</tt> parses the mapping files and generates fully working Java
            source files from these. Thus with <tt class="literal">hbm2java</tt> one could "just" provide the
            <tt class="literal">.hbm</tt> files, and then don't worry about hand-writing/coding the Java files.
        </p><p>
            <tt class="literal">java -cp</tt> <span class="emphasis"><em>hibernate_classpaths</em></span>

            <tt class="literal">net.sf.hibernate.tool.hbm2java.CodeGenerator</tt> <span class="emphasis"><em> options
            mapping_files</em></span>
        </p><div class="table"><a name="d0e7955"></a><p class="title"><b>Table&nbsp;17.5.&nbsp;Code Generator Command Line Options</b></p><table summary="Code Generator Command Line Options" border="1"><colgroup><col><col></colgroup><thead><tr><th>Option</th><th>Description</th></tr></thead><tbody><tr><td><tt class="literal">--output=</tt><span class="emphasis"><em>output_dir</em></span></td><td>root directory for generated code</td></tr><tr><td><tt class="literal">--config=</tt><span class="emphasis"><em>config_file</em></span></td><td>optional file for configuring hbm2java</td></tr></tbody></table></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="toolsetguide-s2-1"></a>17.2.1.&nbsp;The config file (optional)</h3></div></div><div></div></div><p>

                The config file provides for a way to specify multiple "renderers" for the source code
                and to declare <tt class="literal">&lt;meta&gt;</tt> attributes that is "global" in scope. See
                more about this in the <tt class="literal">&lt;meta&gt;</tt> attribute section.
            </p><pre class="programlisting">&lt;codegen&gt;
    &lt;meta attribute="implements"&gt;codegen.test.IAuditable&lt;/meta&gt;
    &lt;generate renderer="net.sf.hibernate.tool.hbm2java.BasicRenderer"/&gt;

    &lt;generate
        package="autofinders.only"
        suffix="Finder"
        renderer="net.sf.hibernate.tool.hbm2java.FinderRenderer"/&gt;
&lt;/codegen&gt;</pre><p>
                This config file declares a global meta attribute "implements" and specify two renderers, the
                default one (BasicRenderer) and a renderer that generates Finder's (See more in "Basic Finder
                generation" below).
            </p><p>
                The second renderer is provided with a package and suffix attribute.
            </p><p>
                The package attribute specifies that the generated source files from this renderer should be
                placed here instead of the package scope specified in the <tt class="literal">.hbm</tt> files.
            </p><p>

                The suffix attribute specifies the suffix for generated files. E.g. here a file named
                <tt class="literal">Foo.java</tt> would be <tt class="literal">FooFinder.java</tt> instead.
            </p></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="toolsetguide-s2-2"></a>17.2.2.&nbsp;The <tt class="literal">meta</tt> attribute</h3></div></div><div></div></div><p>
                The <tt class="literal">&lt;meta&gt;</tt> tag is a simple way of annotating the <tt class="literal">hbm.xml</tt>

                with information, so tools have a natural place to store/read information that is not directly related
                to the Hibernate core.
            </p><p>
                You can use the <tt class="literal">&lt;meta&gt;</tt> tag to tell <tt class="literal">hbm2java</tt> to only
                generate "protected" setters, have classes always implement a certain set of interfaces or
                even have them extend a certain base class and even more.
            </p><p>
                The following example:
            </p><pre class="programlisting">&lt;class name="Person"&gt;
    &lt;meta attribute="class-description"&gt;

        Javadoc for the Person class
        @author Frodo
    &lt;/meta&gt;
    &lt;meta attribute="implements"&gt;IAuditable&lt;/meta&gt;
    &lt;id name="id" type="long"&gt;
        &lt;meta attribute="scope-set"&gt;protected&lt;/meta&gt;

        &lt;generator class="increment"/&gt;
    &lt;/id&gt;
    &lt;property name="name" type="string"&gt;
        &lt;meta attribute="field-description"&gt;The name of the person&lt;/meta&gt;
    &lt;/property&gt;

&lt;/class&gt;</pre><p>
                will produce something like the following (code shortened for better understanding). Notice the
                Javadoc comment and the protected set methods:
            </p><pre class="programlisting">// default package

import java.io.Serializable;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

/** 
 *         Javadoc for the Person class
 *         @author Frodo
 *     
 */
public class Person implements Serializable, IAuditable {

    /** identifier field */
    public Long id;

    /** nullable persistent field */
    public String name;

    /** full constructor */
    public Person(java.lang.String name) {
        this.name = name;
    }

    /** default constructor */
    public Person() {
    }

    public java.lang.Long getId() {
        return this.id;
    }

    protected void setId(java.lang.Long id) {
        this.id = id;
    }

    /** 
     * The name of the person
     */
    public java.lang.String getName() {
        return this.name;
    }

    public void setName(java.lang.String name) {
        this.name = name;
    }

}</pre><div class="table"><a name="d0e8044"></a><p class="title"><b>Table&nbsp;17.6.&nbsp;Supported meta tags</b></p><table summary="Supported meta tags" border="1"><colgroup><col><col></colgroup><thead><tr><th>Attribute</th><th>Description</th></tr></thead><tbody><tr><td><tt class="literal">class-description</tt></td><td>inserted into the javadoc for classes</td></tr><tr><td><tt class="literal">field-description</tt></td><td>inserted into the javadoc for fields/properties</td></tr><tr><td><tt class="literal">implements</tt></td><td>interface the class should implement</td></tr><tr><td><tt class="literal">extends</tt></td><td>class the class should extend (ignored for subclasses)</td></tr><tr><td><tt class="literal">generated-class</tt></td><td>overrule the name of the actual class generated</td></tr><tr><td><tt class="literal">scope-class</tt></td><td>scope for class </td></tr><tr><td><tt class="literal">scope-set</tt></td><td>scope for setter method</td></tr><tr><td><tt class="literal">scope-get</tt></td><td>scope for getter method</td></tr><tr><td><tt class="literal">scope-field</tt></td><td>scope for actual field</td></tr><tr><td><tt class="literal">use-in-tostring</tt></td><td>include this property in the <tt class="literal">toString()</tt></td></tr><tr><td><tt class="literal">bound</tt></td><td>add propertyChangeListener support for a property</td></tr><tr><td><tt class="literal">constrained</tt></td><td>bound + vetoChangeListener support for a property</td></tr><tr><td><tt class="literal">gen-property</tt></td><td>property will not be generated if false (use with care)</td></tr><tr><td><tt class="literal">finder-method</tt></td><td>see "Basic finder generator" below</td></tr><tr><td><tt class="literal">session-method</tt></td><td>see "Basic finder generator" below</td></tr></tbody></table></div><p>

                Attributes declared via the <tt class="literal">&lt;meta&gt;</tt> tag are per default
                "inherited" inside an <tt class="literal">hbm.xml</tt> file.
            </p><p>
                What does that mean? It means that if you e.g want to have all your classes
                implement <tt class="literal">IAuditable</tt> then you just add an
                <tt class="literal">&lt;meta attribute="implements"&gt;IAuditable&lt;/meta&gt;</tt> in the top of
                the <tt class="literal">hbm.xml</tt> file, just after
                <tt class="literal">&lt;hibernate-mapping&gt;</tt>. Now all classes defined in that
                <tt class="literal">hbm.xml</tt> file will implement <tt class="literal">IAuditable</tt>!
                (Except if a class also has an "implements" meta attribute, because local specified
                meta tags always overrules/replaces any inherited meta tags).
            </p><p>

                Note: This applies to <span class="emphasis"><em>all</em></span> <tt class="literal">&lt;meta&gt;</tt>-tags.
                Thus it can also e.g. be used to specify that all fields should be declare protected,
                instead of the default private. This is done by adding <tt class="literal">&lt;meta
                attribute="scope-field"&gt;protected&lt;/meta&gt;</tt> at e.g. just under the
                <tt class="literal">&lt;class&gt;</tt> tag and all fields of that class will be protected.
            </p><p>
                To avoid having a <tt class="literal">&lt;meta&gt;</tt>-tag inherited then you can simply
                specify <tt class="literal">inherit="false"</tt> for the attribute, e.g.
                <tt class="literal">&lt;meta attribute="scope-class" inherit="false"&gt;public abstract&lt;/meta&gt;</tt>

                will restrict the "class-scope" to the current class, not the subclasses.
            </p></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="toolsetguide-s2-3"></a>17.2.3.&nbsp;Basic finder generator</h3></div></div><div></div></div><p>
                It is now possible to have <tt class="literal">hbm2java</tt> generate basic finders for
                Hibernate properties. This requires two things in the <tt class="literal">hbm.xml</tt>
                files.
            </p><p>
                The first is an indication of which fields you want to generate finders for. You indicate
                that with a meta block inside a property tag such as:
            </p><pre class="programlisting">&lt;property name="name" column="name" type="string"&gt;

     &lt;meta attribute="finder-method"&gt;findByName&lt;/meta&gt;
&lt;/property&gt;</pre><p>
                The finder method name will be the text enclosed in the meta tags.
            </p><p>
                The second is to create a config file for hbm2java of the format:
            </p><pre class="programlisting">&lt;codegen&gt;
    &lt;generate renderer="net.sf.hibernate.tool.hbm2java.BasicRenderer"/&gt;

    &lt;generate suffix="Finder" renderer="net.sf.hibernate.tool.hbm2java.FinderRenderer"/&gt;
&lt;/codegen&gt;</pre><p>
                 And then use the param to <tt class="literal">hbm2java --config=xxx.xml</tt> where
                 <tt class="literal">xxx.xml</tt> is the config file you just created.
            </p><p>
                 An optional parameter is meta tag at the class level of the format:
            </p><pre class="programlisting">&lt;meta attribute="session-method"&gt;

    com.whatever.SessionTable.getSessionTable().getSession();
&lt;/meta&gt;</pre><p>
                 Which would be the way in which you get sessions if you use the
                 <span class="emphasis"><em>Thread Local Session</em></span> pattern (documented in the Design Patterns
                 area of the Hibernate website).
            </p></div></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="toolsetguide-s3"></a>17.3.&nbsp;Mapping File Generation</h2></div></div><div></div></div><p>
            A skeletal mapping file may be generated from compiled persistent classes using
            a command line utility called <tt class="literal">MapGenerator</tt>. This utility is part of 
            the Hibernate Extensions package.
        </p><p>

            The Hibernate mapping generator provides a mechanism to produce mappings from
            compiled classes. It uses Java reflection to find <span class="emphasis"><em>properties</em></span>
            and uses heuristics to guess an appropriate mapping from the property type.
            The generated mapping is intended to be a starting point only. There is no way to produce
            a full Hibernate mapping without extra input from the user. However, the tool does
            take away some of the repetitive "grunt" work involved in producing a mapping.
        </p><p>
            Classes are added to the mapping one at a time. The tool will reject
            classes that it judges are are not <span class="emphasis"><em>Hibernate persistable</em></span>.
        </p><p>
            To be <span class="emphasis"><em>Hibernate persistable</em></span> a class
        </p><div class="itemizedlist"><ul type="disc" compact><li><p>must not be a primitive type</p></li><li><p>must not be an array</p></li><li><p>must not be an interface</p></li><li><p>must not be a nested class</p></li><li><p>must have a default (zero argument) constructor.</p></li></ul></div><p>

            Note that interfaces and nested classes actually are persistable by Hibernate, but
            this would not usually be intended by the user.
        </p><p>
            <tt class="literal">MapGenerator</tt> will climb the superclass chain of all added classes attempting
            to add as many Hibernate persistable superclasses as possible to the same database table.
            The search stops as soon as a property is found that has a name appearing on a list of
            <span class="emphasis"><em>candidate UID names</em></span>.
        </p><p>
            The default list of candidate UID property names is: <tt class="literal">uid</tt>, <tt class="literal">UID</tt>,
            <tt class="literal">id</tt>, <tt class="literal">ID</tt>, <tt class="literal">key</tt>, <tt class="literal">KEY</tt>,
            <tt class="literal">pk</tt>, <tt class="literal">PK</tt>.
        </p><p>

            Properties are discovered when there are two methods in the class, a setter and a getter, where the
            type of the setter's single argument is the same as the return type of the zero argument getter,
            and the setter returns <tt class="literal">void</tt>. Furthermore, the setter's name must start with the
            string <tt class="literal">set</tt> and either the getter's name starts with <tt class="literal">get</tt> or
            the getter's name starts with <tt class="literal">is</tt> and the type of the property is boolean. In
            either case, the remainder of their names must match. This matching portion is the name of
            the property, except that the initial character of the property name is made lower case if
            the second letter is lower case.
        </p><p>
            The rules for determining the database type of each property are as follows:
        </p><div class="orderedlist"><ol type="1" compact><li><p>

                    If the Java type is <tt class="literal">Hibernate.basic()</tt>, then the property is a
                    simple column of that type.
                </p></li><li><p>
                    For <tt class="literal">hibernate.type.Type</tt> custom types and <tt class="literal">PersistentEnum</tt>
                    a simple column is used as well.
                </p></li><li><p>
                    If the property type is an array, then a Hibernate array is used, and <tt class="literal">MapGenerator</tt>

                    attempts to reflect on the array element type.
                </p></li><li><p>
                    If the property has type <tt class="literal">java.util.List</tt>, <tt class="literal">java.util.Map</tt>, or
                    <tt class="literal">java.util.Set</tt>, then the corresponding Hibernate types are used, but
                    <tt class="literal">MapGenerator</tt> cannot further process the insides of these types.
                </p></li><li><p>
                    If the property's type is any other class, <tt class="literal">MapGenerator</tt> defers the decision
                    on the database representation until all classes have been processed. At this point, if the
                    class was discovered through the superclass search described above, then the property is
                    an <tt class="literal">many-to-one</tt> association. If the class has any properties, then it is
                    a <tt class="literal">component</tt>. Otherwise it is serializable, or not persistable.
                </p></li></ol></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="toolsetguide-s3-1"></a>17.3.1.&nbsp;Running the tool</h3></div></div><div></div></div><p>

                The tool writes XML mappings to standard out and/or to a file.
            </p><p>
                When invoking the tool you must place your compiled classes on the classpath.
            </p><p>
                <tt class="literal">java -cp </tt><span class="emphasis"><em>hibernate_and_your_class_classpaths</em></span>
                <tt class="literal">net.sf.hibernate.tool.class2hbm.MapGenerator</tt> <span class="emphasis"><em>options and
                classnames</em></span>
            </p><p>

                There are two modes of operation: command line or interactive.
            </p><p>
                The interactive mode is selected by providing the single command line argument
                <tt class="literal">--interact</tt>. This mode provides a prompt response console. Using it you
                can set the UID property name for each class using the <tt class="literal">uid=XXX</tt> command
                where <tt class="literal">XXX</tt> is the UID property name. Other command alternatives are simply
                a fully qualified class name, or the command done which emits the XML and terminates.
            </p><p>
                In command line mode the arguments are the options below interspersed with fully qualified
                class names of the classes to be processed. Most of the options are meant to be used
                multiple times; each use affects subsequently added classes.
            </p><div class="table"><a name="d0e8415"></a><p class="title"><b>Table&nbsp;17.7.&nbsp;MapGenerator Command Line Options</b></p><table summary="MapGenerator Command Line Options" border="1"><colgroup><col><col></colgroup><thead><tr><th>Option</th><th>Description</th></tr></thead><tbody><tr><td><tt class="literal">--quiet</tt></td><td>don't output the O-R Mapping to stdout</td></tr><tr><td><tt class="literal">--setUID=uid</tt></td><td>set the list of candidate UIDs to the singleton uid</td></tr><tr><td><tt class="literal">--addUID=uid</tt></td><td>add uid to the front of the list of candidate UIDs</td></tr><tr><td><tt class="literal">--select=</tt><span class="emphasis"><em>mode</em></span></td><td>mode use select mode <span class="emphasis"><em>mode</em></span>(e.g.,
                            <span class="emphasis"><em>distinct</em></span> or <span class="emphasis"><em>all</em></span>) for subsequently
                            added classes</td></tr><tr><td><tt class="literal">--depth=&lt;small-int&gt;</tt></td><td>limit the depth of component data recursion for subsequently added classes</td></tr><tr><td><tt class="literal">--output=my_mapping.xml</tt></td><td>output the O-R Mapping to a file</td></tr><tr><td><span class="emphasis"><em>full.class.Name</em></span></td><td>add the class to the mapping</td></tr><tr><td><tt class="literal">--abstract=</tt><span class="emphasis"><em>full.class.Name</em></span></td><td>see below</td></tr></tbody></table></div><p>

                The abstract switch directs the map generator tool to ignore specific super classes so
                that classes with common inheritance are not mapped to one large table. For instance,
                consider these class hierarchies:
            </p><p>
                <tt class="literal">Animal--&gt;Mammal--&gt;Human</tt>
            </p><p>
                <tt class="literal">Animal--&gt;Mammal--&gt;Marsupial--&gt;Kangaroo</tt>
            </p><p>

                If the <tt class="literal">--abstract</tt>switch is <span class="emphasis"><em>not</em></span> used, all classes will
                be mapped as subclasses of <tt class="literal">Animal</tt>, resulting in one large table containing
                all the properties of all the classes plus a discriminator column to indicate which subclass is
                actually stored. If <tt class="literal">Mammal</tt> is marked as <tt class="literal">abstract</tt>,
                <tt class="literal">Human</tt> and <tt class="literal">Marsupial</tt> will be mapped to
                separate <tt class="literal">&lt;class&gt;</tt> declarations and stored in separate tables.
                <tt class="literal">Kangaroo</tt> will still be a subclass of <tt class="literal">Marsupial</tt>

                unless <tt class="literal">Marsupial</tt> is also marked as <tt class="literal">abstract</tt>.
            </p></div></div></div></div>
</body></html>