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

Hibernate example source code file (tutorial_native.xml)

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

Java - Hibernate tags/keywords

cdata, event, guide, hibernate, hibernate, in, java, java, sql, the, the, this, this, xml

The Hibernate tutorial_native.xml source code

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">

<chapter id="hibernate-gsg-tutorial-basic">
    <title>Tutorial Using Native Hibernate APIs and hbm.xml Mappings

    <para>
      This tutorial is located within the download bundle under <filename>basic/.
    </para>
    <itemizedlist>
      <title>Objectives
      <listitem>
        <para>
          using Hibernate mapping files (<phrase>hbm.xml) to provide mapping information
        </para>
      </listitem>
      <listitem>
        <para>
          using the <phrase>native Hibernate APIs
        </para>
      </listitem>
    </itemizedlist>


    <section id="hibernate-gsg-tutorial-basic-config">
        <title>The Hibernate configuration file

        <para>
            The resource file <filename>hibernate.cfg.xml defines Hibernate configuration
            information.
        </para>

        <para>
            The <varname>connection.driver_class, connection.url,
            <varname>connection.username and connection.password
            <varname>property elements define JDBC connection information. These tutorials utilize the H2
            in-memory database, So the values of these properties are all specific to running H2 in its in-memory mode.
            <varname>connection.pool_size is used to configure the number of connections in Hibernate's
            built-in connection pool.
        </para>

        <important>
            <para>
                The built-in Hibernate connection pool is in no way intended for production use. It lacks several
                features found on production-ready connection pools.  See the section discussion in <citetitle
                pubwork="book">Hibernate Developer Guide</citetitle> for further information.
            </para>
        </important>

        <para>
            The <varname>dialect property specifies the particular SQL variant with which Hibernate will
            converse.
        </para>

        <tip>
            <para>
                In most cases, Hibernate is able to properly determine which dialect to use. This is particularly useful
                if your application targets multiple databases.  This is discussed in detail in the <citetitle
                pubwork="book">Hibernate Developer Guide</citetitle>
            </para>
        </tip>

        <para>
            The <varname>hbm2ddl.auto property enables automatic generation of database schemas directly into
            the database.
        </para>

        <para>
            Finally, add the mapping file(s) for persistent classes to the configuration.  The <option>resource
            attribute of the <varname>mapping element causes Hibernate to attempt to locate that mapping as a
            classpath resource, using a <classname>java.lang.ClassLoader lookup.
        </para>

    </section>


    <section id="hibernate-gsg-tutorial-basic-entity">
        <title>The entity Java class
        <para>
            The entity class for this tutorial is <classname>org.hibernate.tutorial.hbm.Event.
        </para>
        <itemizedlist>
          <title>Notes About the Entity
          <listitem>
            <para>
              This class uses standard JavaBean naming conventions for property getter and setter methods, as well as
              private visibility for the fields. Although this is the recommended design, it is not required.
            </para>
          </listitem>
          <listitem>
            <para>
              The <methodname>no-argument constructor, which is also a JavaBean convention, is a
              requirement for all persistent classes. Hibernate needs to create objects for you, using Java
              Reflection. The constructor can be private. However, package or public visibility is required for runtime
              proxy generation and efficient data retrieval without bytecode instrumentation.
            </para>
          </listitem>
        </itemizedlist>
    </section>


    <section id="hibernate-gsg-tutorial-basic-mapping">
        <title>The mapping file
        <para>
            The <filename>hbm.xml mapping file for this tutorial is the classpath resource
            <filename>org/hibernate/tutorial/hbm/Event.hbm.xml as we saw in
            <xref linkend="hibernate-gsg-tutorial-basic-config"/>
        </para>

        <para>
            Hibernate uses the mapping metadata to determine how to load and store objects of the persistent class. The
            Hibernate mapping file is one choice for providing Hibernate with this metadata.
        </para>

        <example id="hibernate-gsg-tutorial-basic-mapping-class">
            <title>The class mapping element
            <programlisting role="XML">
    ...
</class>]]>
        </example>

        <orderedlist>
            <title>Functions of the class mapping element
            <listitem>
                <para>
                    The <option>name attribute (combined here with the  attribute from
                    the containing <varname>hibernate-mapping element) names the FQN of the class to be
                    defined as an entity.
                </para>
            </listitem>
            <listitem>
                <para>
                    The <option>table attribute names the database table which contains the data for this
                    entity.
                </para>
            </listitem>
        </orderedlist>

        <para>
            Instances of the <classname>Event class are now mapped to rows in the
            <database class="table">EVENTS table.
        </para>

        <example id="hibernate-gsg-tutorial-basic-mapping-id">
            <title>The id mapping element
            <programlisting role="XML">
    ...
</id>]]>
        </example>

        <para>
            Hibernate uses the property named by the <varname>id element to uniquely identify rows in the
            table.
        </para>

        <important>
            <!-- Again, perhaps more sense moving this to the Dev Guide -->
            <para>
                It is not required for the <varname>id element to map to the table's actual primary key
                column(s), but it is the normal convention.  Tables mapped in Hibernate do not even need to define
                primary keys. However, it is strongly recommend that all schemas define proper referential
                integrity. Therefore <varname>id and primary key are used interchangeably
                throughout Hibernate documentation.
            </para>
        </important>
        <para>
            The <varname>id element here identifies the EVENT_ID column as
            the primary key of the <database class="table">EVENTS table. It also identifies the
            <varname>id property of the Event class as the property containing the
            identifier value.
        </para>
        <para>
            The <varname>generator element nested inside the id element informs Hibernate
            about which strategy is used to generated primary key values for this entity.  This example uses a simple
            incrementing count.
        </para>

        <example id="hibernate-gsg-tutorial-basic-mapping-property">
            <title>The property mapping element
            <programlisting role="XML">
<property name="title"/>]]>
        </example>

        <para>
            The two <varname>property elements declare the remaining two properties of the
            <classname>Event class: date and title. The
            <varname>date property mapping includes the  attribute, but the
            <varname>title does not. In the absence of a  attribute, Hibernate
            uses the property name as the column name. This is appropriate for <varname>title, but since
            <varname>date is a reserved keyword in most databases, you need to specify a non-reserved
            word for the column name.
        </para>
        <para>
            The <varname>title mapping also lacks a  attribute. The types
            declared and used in the mapping files are neither Java data types nor SQL database types. Instead,
            they are <firstterm>Hibernate mapping types. Hibernate mapping types are
            converters which translate between Java and SQL data types. Hibernate attempts to determine the correct
            conversion and mapping type autonomously if the <option>type attribute is not present in the
            mapping, by using Java reflection to determine the Java type of the declared property and using a
            default mapping type for that Java type.
        </para>
        <para>
            In some cases this automatic detection might not chose the default you expect or need, as seen with the
            <varname>date property. Hibernate cannot know if the property, which is of type
            <classname>java.util.Date, should map to a SQL DATE,
            <database class="datatype">TIME, or TIMESTAMP datatype.
            Full date and time information is preserved by mapping the property to a <type>timestamp converter,
            which identifies an instance of the class <classname>org.hibernate.type.TimestampType.
        </para>

        <tip>
            <!-- This tip probably makes more sense in the Dev Guide -->
            <para>
                Hibernate determines the mapping type using reflection when the mapping files are processed. This
                process adds overhead in terms of time and resources. If startup performance is important, consider
                explicitly defining the type to use.
            </para>
        </tip>

    </section>

    <section id="hibernate-gsg-tutorial-basic-test">
        <title>Example code
        <para>
            The <classname>org.hibernate.tutorial.hbm.NativeApiIllustrationTest class illustrates using
            the Hibernate <phrase>native API.
        </para>
        <note>
            <para>
                The examples in these tutorials are presented as JUnit tests, for ease of use.  One benefit of this
                approach is that <methodname>setUp and tearDown roughly illustrate
                how a <interfacename>org.hibernate.SessionFactory is created at the start-up of an
                application and closed<!--destroyed?--> at the end of the application lifecycle.
            </para>
        </note>

        <example id="hibernate-gsg-tutorial-basic-test-setUp">
            <title>Obtaining the org.hibernate.SessionFactory
            <programlisting role="JAVA">protected void setUp() throws Exception {
    // A SessionFactory is set up once for an application
    sessionFactory = new Configuration()
            .configure() // configures settings from hibernate.cfg.xml
            .buildSessionFactory();
}</programlisting>
        </example>

        <procedure>
          <title>Tutorial Workflow
          <step>
            <title>The configuration is loaded.
            <para>
              The <classname>org.hibernate.cfg.Configuration class is the first thing to notice. In this
              tutorial, all configuration details are located in the <filename>hibernate.cfg.xml file
              discussed in <xref linkend="hibernate-gsg-tutorial-basic-config"/>.
            </para>
          </step>
          <step>
            <title>The org.hibernate.SessionFactory is created.
            <para>
              The <classname>org.hibernate.cfg.Configuration then creates the
              <interfacename>org.hibernate.SessionFactory which is a thread-safe object that is
              instantiated once to serve the entire application.
            </para>
          </step>
          <step>
            <title>SessionFactory creates Session instances.
            <para>
              The <interfacename>org.hibernate.SessionFactory acts as a factory for
              <interfacename>org.hibernate.Session instances as can be seen in the
              <methodname>testBasicUsage method.  
            <!-- todo : reference to a discussion in dev guide -->
            </para>
          </step>
          <step>
            <title>Sessions perform work.
            <para>
              A <interfacename>org.hibernate.Session should be thought of as a corollary to a "unit of
              work".
            </para>
          </step>
        </procedure>
        
        <example id="hibernate-gsg-tutorial-basic-test-saving">
            <title>Saving entities
            <programlisting role="JAVA">Session session = sessionFactory.openSession();
session.beginTransaction();
session.save( new Event( "Our very first event!", new Date() ) );
session.save( new Event( "A follow up event", new Date() ) );
session.getTransaction().commit();
session.close();</programlisting>
        </example>

        <para>
            <methodname>testBasicUsage first creates some new Event objects and
            hands them over to Hibernate for management, using the <methodname>save method.  Hibernate now
            takes responsibility to perform an <command>INSERT on the database.
        </para>

        <example id="hibernate-gsg-tutorial-basic-test-list">
            <title>Obtaining a list of entities
            <programlisting role="JAVA">
        </example>

        <para>
          <methodname>testBasicUsage illustrates use of the Hibernate Query Language
          (HQL)</firstterm> to load all existing Event objects from the database and generate the
          appropriate <literal>SELECT SQL, send it to the database and populate Event
          objects with the result set data.
        </para>
    </section>

    <section id="hibernate-gsg-tutorial-annotations-further">
        <title>Take it further!
        <itemizedlist>
          <title>Practice Exercises
            <listitem>
                <para>
                    Reconfigure the examples to connect to your own persistent relational database.
                </para>
            </listitem>
            <listitem>
                <para>
                    With help of the <citetitle pubwork="book">Developer Guide, add an association to
                    the <classname>Event entity to model a message thread.
                </para>
            </listitem>
        </itemizedlist>
    </section>

</chapter>

Other Hibernate examples (source code examples)

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

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

#1 New Release!

FP Best Seller

 

new blog posts

 

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

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