alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  
"); out.println("<td>" + dateFormatter.format(event.getDate()) + ""); out.println("</tr>"); } out.println("</table>"); } }]]></programlisting> <para> Finally, the <literal>store action is dispatched to the <literal>createAndStoreEvent() method, which also uses the <literal>Session of the current thread: </para> <programlisting role="JAVA"> <para> The servlet is now complete. A request to the servlet will be processed in a single <literal>Session and Transaction. As earlier in the standalone application, Hibernate can automatically bind these objects to the current thread of execution. This gives you the freedom to layer your code and access the <literal>SessionFactory in any way you like. Usually you would use a more sophisticated design and move the data access code into data access objects (the DAO pattern). See the Hibernate Wiki for more examples. </para> </section> <section id="tutorial-webapp-deploy"> <title>Deploying and testing <para> To deploy this application for testing we must create a Web ARchive (WAR). First we must define the WAR descriptor as <filename>src/main/webapp/WEB-INF/web.xml </para> <programlisting role="XML"> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <servlet> <servlet-name>Event Manager <servlet-class>org.hibernate.tutorial.web.EventManagerServlet </servlet> <servlet-mapping> <servlet-name>Event Manager <url-pattern>/eventmanager </servlet-mapping> </web-app>]]> <para> To build and deploy call <literal>mvn package in your project directory and copy the <filename>hibernate-tutorial.war file into your Tomcat <filename>webapps directory. </para> <note> <para> If you do not have Tomcat installed, download it from <ulink url="http://tomcat.apache.org/"/> and follow the installation instructions. Our application requires no changes to the standard Tomcat configuration. </para> </note> <para> Once deployed and Tomcat is running, access the application at <literal>http://localhost:8080/hibernate-tutorial/eventmanager. Make sure you watch the Tomcat log to see Hibernate initialize when the first request hits your servlet (the static initializer in <literal>HibernateUtil is called) and to get the detailed output if any exceptions occurs. </para> </section> </section> <section id="tutorial-summary" revision="1"> <title>Summary <para> This tutorial covered the basics of writing a simple standalone Hibernate application and a small web application. More tutorials are available from the Hibernate <ulink url="http://hibernate.org">website. </para> </section> </chapter>

Other Hibernate examples (source code examples)

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

Hibernate example source code file (tutorial.xml)

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

Java - Hibernate tags/keywords

cdata, cdata, event, hibernate, hibernate, info, java, java, person, the, the, this, util, xml, you

The Hibernate tutorial.xml source code

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

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

<chapter id="tutorial">
    <title>Tutorial

    <para>
        Intended for new users, this chapter provides an step-by-step introduction
        to Hibernate, starting with a simple application using an in-memory database.  The
        tutorial is based on an earlier tutorial developed by Michael Gloegl.  All
        code is contained in the <filename>tutorials/web directory of the project
        source.
    </para>

    <important>
        <para>
            This tutorial expects the user have knowledge of both Java and
            SQL.  If you have a limited knowledge of JAVA or SQL, it is advised
            that you start with a good introduction to that technology prior
            to attempting to learn Hibernate.
        </para>
    </important>

    <note>
        <para>
            The distribution contains another example application under
            the <filename>tutorial/eg project source
            directory.
        </para>
    </note>

    <section id="tutorial-firstapp">
        <title>Part 1 - The first Hibernate Application

        <para>
            For this example, we will set up a small database application that can store
            events we want to attend and information about the host(s) of these events.
        </para>

        <note>
            <para>
                Although you can use whatever database you feel comfortable using, we
                will use <ulink url="http://hsqldb.org/">HSQLDB (an in-memory,
                Java database) to avoid describing installation/setup of any particular
                database servers.
            </para>
        </note>

        <section id="tutorial-firstapp-setup">
            <title>Setup

            <para>
                The first thing we need to do is to set up the development environment.  We
                will be using the "standard layout" advocated by alot of build tools such
                as <ulink url="http://maven.org">Maven.  Maven, in particular, has a
                good resource describing this <ulink url="http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html">layout.
                As this tutorial is to be a web application, we will be creating and making
                use of <filename>src/main/java, src/main/resources
                and <filename>src/main/webapp directories.
            </para>

            <para>
                We will be using Maven in this tutorial, taking advantage of its
                transitive dependency management capabilities as well as the ability of
                many IDEs to automatically set up a project for us based on the maven descriptor.
            </para>

        <programlisting role="XML">

    <groupId>org.hibernate.tutorials
    <artifactId>hibernate-tutorial
    <version>1.0.0-SNAPSHOT
    <name>First Hibernate Tutorial

    <build>
         <!-- we dont want the version to be part of the generated war file name -->
         <finalName>${artifactId}
    </build>

    <dependencies>
        <dependency>
            <groupId>org.hibernate
            <artifactId>hibernate-core
        </dependency>

        <!-- Because this is a web app, we also have a dependency on the servlet api. -->
        <dependency>
            <groupId>javax.servlet
            <artifactId>servlet-api
        </dependency>

        <!-- Hibernate uses slf4j for logging, for our purposes here use the simple backend -->
        <dependency>
            <groupId>org.slf4j
            <artifactId>slf4j-simple
        </dependency>

        <!-- Hibernate gives you a choice of bytecode providers between cglib and javassist -->
        <dependency>
            <groupId>javassist
            <artifactId>javassist
        </dependency>
    </dependencies>

</project>]]>

            <tip>
                <para>
                    It is not a requirement to use Maven.  If you wish to use something else to
                    build this tutorial (such as Ant), the layout will remain the same.  The only
                    change is that you will need to manually account for all the needed
                    dependencies.  If you use something like <ulink url="http://ant.apache.org/ivy/">Ivy
                    providing transitive dependency management you would still use the dependencies
                    mentioned below.  Otherwise, you'd need to grab <emphasis>all
                    dependencies, both explicit and transitive, and add them to the project's
                    classpath.  If working from the Hibernate distribution bundle, this would mean
                    <filename>hibernate3.jar, all artifacts in the
                    <filename>lib/required directory and all files from either the
                    <filename>lib/bytecode/cglib or lib/bytecode/javassist
                    directory; additionally you will need both the servlet-api jar and one of the slf4j
                    logging backends.
                </para>
            </tip>

            <para>
                Save this file as <filename>pom.xml in the project root directory.
            </para>
        </section>


        <section id="tutorial-firstapp-firstclass">
            <title>The first class
            
            <para>
                Next, we create a class that represents the event we want to store in the
                database; it is a simple JavaBean class with some properties:
            </para>

            <programlisting role="JAVA">

            <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.
                Hibernate can also access fields directly,  the benefit of accessor
                methods is robustness for refactoring.
            </para>

            <para>
                The <literal>id property holds a unique identifier value
                for a particular event.  All persistent entity classes (there are
                less important dependent classes as well) will need such an identifier
                property if we want to use the full feature set of Hibernate. In fact,
                most applications, especially web applications, need to distinguish
                objects by identifier, so you should consider this a feature rather
                than a limitation.  However, we usually do not manipulate the identity
                of an object, hence the setter method should be private.  Only Hibernate
                will assign identifiers when an object is saved.  Hibernate can access
                public, private, and protected accessor methods, as well as public,
                private and protected fields directly.  The choice is up to you and
                you can match it to fit your application design.
            </para>

            <para>
                The no-argument constructor is a requirement for all persistent
                classes; Hibernate has 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>

            <para>
                Save this file to the <filename>src/main/java/org/hibernate/tutorial/domain
                directory.
            </para>
        </section>

        <section id="tutorial-firstapp-mapping">
            <title>The mapping file

            <para>
                Hibernate needs to know how to load and store objects of the
                persistent class.  This is where the Hibernate mapping file
                comes into play. The mapping file tells Hibernate what table in
                the database it has to access, and what columns in that table
                it should use.
            </para>

            <para>
                The basic structure of a mapping file looks like this:
            </para>

            <programlisting role="XML">
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="org.hibernate.tutorial.domain">
[...]
</hibernate-mapping>]]>

            <para>
                Hibernate DTD is sophisticated.  You can use it for auto-completion
                of XML mapping elements and attributes in your editor or IDE.
                Opening up the DTD file in your text editor is the easiest way to
                get an overview of all elements and attributes, and to view the
                defaults, as well as some comments.  Hibernate will not load the
                DTD file from the web, but first look it up from the classpath of
                the application.  The DTD file is included in
                <filename>hibernate-core.jar (it is also included in the
                <filename>hibernate3.jar, if using the distribution bundle).
            </para>

            <important>
                <para>
                    We will omit the DTD declaration in future examples to shorten the code. It is,
                    of course, not optional.
                </para>
            </important>

            <para>
                Between the two <literal>hibernate-mapping tags, include a
                <literal>class element. All persistent entity classes (again, there
                might be dependent classes later on, which are not first-class entities) need
                a mapping to a table in the SQL database:
            </para>

            <programlisting role="XML">

    <class name="Event" table="EVENTS">

    </class>

</hibernate-mapping>]]>

            <para>
                So far we have told Hibernate how to persist and load object of
                class <literal>Event to the table
                <literal>EVENTS. Each instance is now represented by a
                row in that table.  Now we can continue by mapping the unique
                identifier property to the tables primary key.  As we do not want
                to care about handling this identifier, we configure Hibernate's
                identifier generation strategy for a surrogate primary key column:
            </para>

            <programlisting role="XML">

    <class name="Event" table="EVENTS">
        <id name="id" column="EVENT_ID">
            <generator class="native"/>
        </id>
    </class>

</hibernate-mapping>]]>

            <para>
                The <literal>id element is the declaration of the
                identifier property.  The <literal>name="id" mapping
                attribute declares the name of the JavaBean property and tells
                Hibernate to use the <literal>getId() and
                <literal>setId() methods to access the property.  The
                column attribute tells Hibernate which column of the
                <literal>EVENTS table holds the primary key value.
            </para>

            <para>
                The nested <literal>generator element specifies the
                identifier generation strategy (aka how are identifier values
                generated?).  In this case we choose <literal>native,
                which offers a level of portability depending on the configured
                database dialect.  Hibernate supports database generated, globally
                unique, as well as application assigned, identifiers.  Identifier
                value generation is also one of Hibernate's many extension points
                and you can plugin in your own strategy.
            </para>

            <tip>
                <para>
                    <literal>native is no longer consider the best strategy in terms of portability.  for further
                    discussion, see <xref linkend="portability-idgen"/>
                </para>
            </tip>

            <para>
                Lastly, we need to tell Hibernate about the remaining entity class
                properties.  By default, no properties of the class are considered
                persistent:
            </para>
            
            <programlisting role="XML">
            
            <para>
                Similar to the <literal>id element, the
                <literal>name attribute of the
                <literal>property element tells Hibernate which getter
                and setter methods to use.  In this case, Hibernate will search
                for <literal>getDate(), setDate(),
                <literal>getTitle() and setTitle()
                methods.
            </para>

            <note>
                <para>
                    Why does the <literal>date property mapping include the
                    <literal>column attribute, but the title
                    does not? Without the <literal>column attribute, Hibernate
                    by default uses the property name as the column name. This works for
                    <literal>title, however, date is a reserved
                    keyword in most databases so you will need to map it to a different name.
                </para>
            </note>

            <para>
                The <literal>title mapping also lacks a type attribute. The
                types declared and used in the mapping files are not Java data types; they are not SQL
                database types either.  These types are called <emphasis>Hibernate mapping types,
                converters which can translate from Java to SQL data types and vice versa.  Again,
                Hibernate will try to determine the correct conversion and mapping type itself if
                the <literal>type attribute is not present in the mapping. In some cases this
                automatic detection using Reflection on the Java class might not have the default you
                expect or need. This is the case with the <literal>date property. Hibernate cannot
                know if the property, which is of <literal>java.util.Date, should map to a
                SQL <literal>date, timestamp, or time column.
                Full date and time information is preserved by mapping the property with a
                <literal>timestamp converter.
            </para>

            <tip>
                <para>
                    Hibernate makes this mapping type determination using reflection when the mapping files
                    are processed.  This can take time and resources, so if startup performance is important
                    you should consider explicitly defining the type to use.
                </para>
            </tip>

            <para>
                Save this mapping file as
                <filename>src/main/resources/org/hibernate/tutorial/domain/Event.hbm.xml.
            </para>

        </section>

        <section id="tutorial-firstapp-configuration" revision="2">
            <title>Hibernate configuration

            <para>
                At this point, you should have the persistent class and its mapping
                file in place. It is now time to configure Hibernate.  First let's set up
                HSQLDB to run in "server mode"
            </para>

            <note>
                <para>
                    We do this do that the data remains between runs.
                </para>
            </note>

            <para>
                We will utilize the Maven exec plugin to launch the HSQLDB server
                by running:
                <command> mvn exec:java -Dexec.mainClass="org.hsqldb.Server" -Dexec.args="-database.0 file:target/data/tutorial"
                You will see it start up and bind to a TCP/IP socket; this is where
                our application will connect later.  If you want to start
                with a fresh database during this tutorial, shutdown HSQLDB, delete
                all files in the <filename>target/data directory,
                and start HSQLDB again.
            </para>

            <para>
                Hibernate will be connecting to the database on behalf of your application, so it needs to know
                how to obtain connections.  For this tutorial we will be using a standalone connection
                pool (as opposed to a <interfacename>javax.sql.DataSource).  Hibernate comes with
                support for two third-party open source JDBC connection pools:
                <ulink url="https://sourceforge.net/projects/c3p0">c3p0 and
                <ulink url="http://proxool.sourceforge.net/">proxool.  However, we will be using the
                Hibernate built-in connection pool for this tutorial.
            </para>

            <caution>
                <para>
                    The built-in Hibernate connection pool is in no way intended for production use.  It
                    lacks several features found on any decent connection pool.
                </para>
            </caution>

            <para>
                For Hibernate's configuration, we can use a simple <literal>hibernate.properties file, a
                more sophisticated <literal>hibernate.cfg.xml file, or even complete
                programmatic setup. Most users prefer the XML configuration file:
            </para>

            <programlisting role="XML">
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">org.hsqldb.jdbcDriver
        <property name="connection.url">jdbc:hsqldb:hsql://localhost
        <property name="connection.username">sa
        <property name="connection.password">

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.HSQLDialect

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update

        <mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/>

    </session-factory>

</hibernate-configuration>]]>

            <note>
                <para>Notice that this configuration file specifies a different DTD
            </note>

            <para>
                You configure Hibernate's <literal>SessionFactory. SessionFactory is a global
                factory responsible for a particular database. If you have several databases, for easier
                startup you should use several <literal><session-factory> configurations in
                several configuration files.
            </para>

            <para>
                The first four <literal>property elements contain the necessary
                configuration for the JDBC connection. The dialect <literal>property
                element specifies the particular SQL variant Hibernate generates.
            </para>

            <tip>
                <para>
                    In most cases, Hibernate is able to properly determine which dialect to use.  See
                    <xref linkend="portability-dialectresolver"/> for more information.
                </para>
            </tip>

            <para>
                Hibernate's automatic session management for persistence contexts is particularly useful
                in this context.  The <literal>hbm2ddl.auto option turns on automatic generation of
                database schemas directly into the database. This can also be turned
                off by removing the configuration option, or redirected to a file with the help of
                the <literal>SchemaExport Ant task. Finally, add the mapping file(s)
                for persistent classes to the configuration.
            </para>

            <para>
                Save this file as <filename>hibernate.cfg.xml into the
                <filename>src/main/resources directory.
            </para>

        </section>

        <section id="tutorial-firstapp-mvn" revision="1">
            <title>Building with Maven

            <para>
                We will now build the tutorial with Maven.  You will need to
                have Maven installed; it is available from the
                <ulink url="http://maven.apache.org/download.html">Maven download page.
                Maven will read the <filename>/pom.xml file we created
                earlier and know how to perform some basic project tasks.  First,
                lets run the <literal>compile goal to make sure we can compile
                everything so far:
            </para>

            <programlisting>

        </section>

        <section id="tutorial-firstapp-helpers" revision="3">
            <title>Startup and helpers

            <para>
                It is time to load and store some <literal>Event
                objects, but first you have to complete the setup with some
                infrastructure code. You have to startup Hibernate by building
                a global <interfacename>org.hibernate.SessionFactory
                object and storing it somewhere for easy access in application code.  A
                <interfacename>org.hibernate.SessionFactory is used to
                obtain <interfacename>org.hibernate.Session instances.
                A <interfacename>org.hibernate.Session represents a
                single-threaded unit of work.  The
                <interfacename>org.hibernate.SessionFactory is a
                thread-safe global object that is instantiated once.
            </para>

            <para>
                We will create a <literal>HibernateUtil helper class that
                takes care of startup and makes accessing the
                <interfacename>org.hibernate.SessionFactory more convenient.
            </para>

            <programlisting role="JAVA">

            <para>
                Save this code as
                <filename>src/main/java/org/hibernate/tutorial/util/HibernateUtil.java
            </para>

            <para>
                This class not only produces the global
                <interfacename>org.hibernate.SessionFactory reference in
                its static initializer; it also hides the fact that it uses a
                static singleton.  We might just as well have looked up the
                <interfacename>org.hibernate.SessionFactory reference from
                JNDI in an application server or any other location for that matter.
            </para>

            <para>
                If you give the <interfacename>org.hibernate.SessionFactory
                a name in your configuration, Hibernate will try to bind it to
                JNDI under that name after it has been built.  Another, better option is to
                use a JMX deployment and let the JMX-capable container instantiate and bind
                a <literal>HibernateService to JNDI. Such advanced options are
                discussed later.
            </para>

            <para>
                You now need to configure a logging
                system.  Hibernate uses commons logging and provides two choices: Log4j and
                JDK 1.4 logging. Most developers prefer Log4j: copy <literal>log4j.properties
                from the Hibernate distribution in the <literal>etc/ directory to
                your <literal>src directory, next to hibernate.cfg.xml.
                If you prefer to have
                more verbose output than that provided in the example configuration, you can change the settings.  By default, only the Hibernate startup message is shown on stdout.
            </para>

            <para>
                The tutorial infrastructure is complete and you are now ready to do some real work with
                Hibernate.
            </para>

        </section>

        <section id="tutorial-firstapp-workingpersistence" revision="5">
            <title>Loading and storing objects

            <para>
                We are now ready to start doing some real work with Hibernate.
                Let's start by writing an <literal>EventManager class
                with a <literal>main() method:
            </para>

            <programlisting role="JAVA">

            <para>
                In <literal>createAndStoreEvent() we created a new
                <literal>Event object and handed it over to Hibernate.
                At that point, Hibernate takes care of the SQL and executes an
                <literal>INSERT on the database.
            </para>

            <para>
                A <interface>org.hibernate.Session is designed to
                represent a single unit of work (a single atomic piece of work
                to be performed).  For now we will keep things simple and assume
                a one-to-one granularity between a Hibernate
                <interface>org.hibernate.Session and a database
                transaction.  To shield our code from the actual underlying
                transaction system we use the Hibernate
                <interfacename>org.hibernate.Transaction API.
                In this particular case we are using JDBC-based transactional
                semantics, but it could also run with JTA.
            </para>

            <para>
                What does <literal>sessionFactory.getCurrentSession() do?
                First, you can call it as many times and anywhere you like
                once you get hold of your
                <interfacename>org.hibernate.SessionFactory.
                The <literal>getCurrentSession() method always returns
                the "current" unit of work.  Remember that we switched
                the configuration option for this mechanism to "thread" in our
                <filename>src/main/resources/hibernate.cfg.xml?
                Due to that setting, the context of a current unit of work is bound
                to the current Java thread that executes the application.
            </para>

            <important>
                <para>
                    Hibernate offers three methods of current session tracking.
                    The "thread" based method is not intended for production use;
                    it is merely useful for prototyping and tutorials such as this
                    one.  Current session tracking is discussed in more detail
                    later on.
                </para>
            </important>

            <para>
                A <interface>org.hibernate.Session begins when the
                first call to <literal>getCurrentSession() is made for
                the current thread.  It is then bound by Hibernate to the current
                thread.  When the transaction ends, either through commit or
                rollback, Hibernate automatically unbinds the
                <interface>org.hibernate.Session from the thread
                and closes it for you. If you call
                <literal>getCurrentSession() again, you get a new
                <interface>org.hibernate.Session and can start a
                new unit of work.
            </para>

            <para>
                Related to the unit of work scope, should the Hibernate
                <interface>org.hibernate.Session be used to execute
                one or several database operations?  The above example uses one
                <interface>org.hibernate.Session for one operation.
                However this is pure coincidence; the example is just not complex
                enough to show any other approach. The scope of a Hibernate
                <interface>org.hibernate.Session is flexible but you
                should never design your application to use a new Hibernate
                <interface>org.hibernate.Session for
                <emphasis>every database operation. Even though it is
                used in the following examples, consider
                <emphasis>session-per-operation an anti-pattern.
                A real web application is shown later in the tutorial which will
                help illustrate this.
            </para>

            <para>
                See <xref linkend="transactions"/> for more information
                about transaction handling and demarcation. The previous
                example also skipped any error handling and rollback.
            </para>

            <para>
                To run this, we will make use of the Maven exec plugin to call our class
                with the necessary classpath setup:
                <command>mvn exec:java -Dexec.mainClass="org.hibernate.tutorial.EventManager" -Dexec.args="store"
            </para>

            <note>
                <para>
                    You may need to perform <command>mvn compile first.
                </para>
            </note>

            <para>
                You should see Hibernate starting up and, depending on your configuration,
                lots of log output. Towards the end, the following line will be displayed:
            </para>

            <programlisting>

            <para>
                This is the <literal>INSERT executed by Hibernate.
            </para>

            <para>
                To list stored events an option is added to the main method:
            </para>

            <programlisting role="JAVA">

            <para>
                A new <literal>listEvents() method is also added:
            </para>

            <programlisting role="JAVA">

            <para>
                Here, we are using a Hibernate Query Language (HQL) query to load all existing
                <literal>Event objects from the database. Hibernate will generate the
                appropriate SQL, send it to the database and populate <literal>Event objects
                with the data. You can create more complex queries with HQL. See <xref linkend="queryhql"/>
                for more information.
            </para>

            <para>
                Now we can call our new functionality, again using the Maven exec plugin:
                <command>mvn exec:java -Dexec.mainClass="org.hibernate.tutorial.EventManager" -Dexec.args="list"
            </para>

        </section>

    </section>

    <section id="tutorial-associations">
        <title>Part 2 - Mapping associations

        <para>
            So far we have mapped a single persistent entity class to a table in
            isolation.  Let's expand on that a bit and add some class associations.
            We will add people to the application and store a list of events in
            which they participate.
        </para>

        <section id="tutorial-associations-mappinguser" revision="1">
            <title>Mapping the Person class

            <para>
                The first cut of the <literal>Person class looks like this:
            </para>

            <programlisting role="JAVA">

            <para>
                Save this to a file named
                <filename>src/main/java/org/hibernate/tutorial/domain/Person.java
            </para>

            <para>
                Next, create the new mapping file as
                <filename>src/main/resources/org/hibernate/tutorial/domain/Person.hbm.xml
            </para>

            <programlisting role="XML">

    <class name="Person" table="PERSON">
        <id name="id" column="PERSON_ID">
            <generator class="native"/>
        </id>
        <property name="age"/>
        <property name="firstname"/>
        <property name="lastname"/>
    </class>

</hibernate-mapping>]]>

            <para>
                Finally, add the new mapping to Hibernate's configuration:
            </para>

            <programlisting role="XML">
<mapping resource="org/hibernate/tutorial/domain/Person.hbm.xml"/>]]>

            <para>
                Create an association between these two entities. Persons
                can participate in events, and events have participants. The design questions
                you have to deal with are: directionality, multiplicity, and collection
                behavior.
            </para>

        </section>

        <section id="tutorial-associations-unidirset" revision="3">
            <title>A unidirectional Set-based association

            <para>
                By adding a collection of events to the <literal>Person
                class, you can easily navigate to the events for a particular person,
                without executing an explicit query - by calling
                <literal>Person#getEvents.  Multi-valued associations
                are represented in Hibernate by one of the Java Collection Framework
                contracts; here we choose a <interfacename>java.util.Set
                because the collection will not contain duplicate elements and the ordering
                is not relevant to our examples:
            </para>

            <programlisting role="JAVA">

            <para>
                Before mapping this association, let's consider the other side.
                We could just keep this unidirectional or create another
                collection on the <literal>Event, if we wanted to be
                able to navigate it from both directions.  This is not necessary,
                from a functional perspective. You can always execute an explicit
                query to retrieve the participants for a particular event.  This
                is a design choice left to you, but what is clear from this
                discussion is the multiplicity of the association: "many" valued
                on both sides is called a <emphasis>many-to-many
                association. Hence, we use Hibernate's many-to-many mapping:
            </para>

            <programlisting role="XML">
    <id name="id" column="PERSON_ID">
        <generator class="native"/>
    </id>
    <property name="age"/>
    <property name="firstname"/>
    <property name="lastname"/>

    <set name="events" table="PERSON_EVENT">
        <key column="PERSON_ID"/>
        <many-to-many column="EVENT_ID" class="Event"/>
    </set>

</class>]]>

            <para>
                Hibernate supports a broad range of collection mappings, a
                <literal>set being most common.  For a many-to-many
                association, or <emphasis>n:m entity relationship, an
                association table is required.  Each row in this table represents
                a link between a person and an event.  The table name is
                decalred using the <literal>table attribute of the
                <literal>set element.  The identifier column name in
                the association, for the person side, is defined with the
                <literal>key element, the column name for the event's
                side with the <literal>column attribute of the
                <literal>many-to-many. You also have to tell Hibernate
                the class of the objects in your collection (the class on the
                other side of the collection of references).
            </para>

            <para>
                The database schema for this mapping is therefore:
            </para>

            <programlisting>

        </section>

        <section id="tutorial-associations-working" revision="2">
            <title>Working the association

            <para>
                Now we will bring some people and events together in a new method in <literal>EventManager:
            </para>

            <programlisting role="JAVA">

            <para>
                After loading a <literal>Person and an
                <literal>Event, simply modify the collection using the
                normal collection methods. There is no explicit call to
                <literal>update() or save();
                Hibernate automatically detects that the collection has been modified
                and needs to be updated. This is called
                <emphasis>automatic dirty checking. You can also try
                it by modifying the name or the date property of any of your
                objects.  As long as they are in <emphasis>persistent
                state, that is, bound to a particular Hibernate
                <interfacename>org.hibernate.Session, Hibernate
                monitors any changes and executes SQL in a write-behind fashion.
                The process of synchronizing the memory state with the database,
                usually only at the end of a unit of work, is called
                <emphasis>flushing.  In our code, the unit of work
                ends with a commit, or rollback, of the database transaction.
            </para>

            <para>
                You can load person and event in different units of work.  Or
                you can modify an object outside of a
                <interfacename>org.hibernate.Session, when it
                is not in persistent state (if it was persistent before, this
                state is called <emphasis>detached).  You can even
                modify a collection when it is detached:
            </para>

            <programlisting role="JAVA">

            <para>
                The call to <literal>update makes a detached object
                persistent again by binding it to a new unit of work, so any
                modifications you made to it while detached can be saved to
                the database. This includes any modifications
                (additions/deletions) you made to a collection of that entity
                object.
            </para>

            <para>
                This is not much use in our example, but it is an important concept you can
                incorporate into your own application. Complete this exercise by adding a new action
                to the  main method of the <literal>EventManager and call it from the command line. If
                you need the identifiers of a person and an event - the <literal>save() method
                returns it (you might have to modify some of the previous methods to return that identifier):
            </para>

            <programlisting role="JAVA">

            <para>
                This is an example of an association between two equally important
                classes : two entities.  As mentioned earlier, there are other
                classes and types in a typical model, usually "less important".
                Some you have already seen, like an <literal>int or a
                <classname>java.lang.String.  We call these classes
                <emphasis>value types, and their instances
                <emphasis>depend on a particular entity.  Instances of
                these types do not have their own identity, nor are they shared
                between entities.  Two persons do not reference the same
                <literal>firstname object, even if they have the same
                first name.  Value types cannot only be found in the JDK , but
                you can also write dependent classes yourself
                such as an <literal>Address or
                <literal>MonetaryAmount class.  In fact, in a Hibernate
                application all JDK classes are considered value types.
            </para>

            <para>
                You can also design a collection of value types.  This is
                conceptually different from a collection of references to other
                entities, but looks almost the same in Java.
            </para>

        </section>

        <section id="tutorial-associations-valuecollections">
            <title>Collection of values

            <para>
                Let's add a collection of email addresses to the
                <literal>Person entity.  This will be represented as a
                <interfacename>java.util.Set of
                <classname>java.lang.String instances:
            </para>
            <programlisting role="JAVA">

            <para>
                The mapping of this <literal>Set is as follows:
            </para>

            <programlisting role="XML">
            <key column="PERSON_ID"/>
            <element type="string" column="EMAIL_ADDR"/>
        </set>]]>

            <para>
                The difference compared with the earlier mapping is the use of
                the <literal>element part which tells Hibernate that the
                collection does not contain references to another entity, but is
                rather a collection whose elements are values types, here specifically
                of type <literal>string.  The lowercase name tells you
                it is a Hibernate mapping type/converter.  Again the
                <literal>table attribute of the set
                element determines the table name for the collection.   The
                <literal>key element defines the foreign-key column
                name in the collection table. The <literal>column
                attribute in the <literal>element element defines the
                column name where the email address values will actually
                be stored.
            </para>

            <para>
                Here is the updated schema:
            </para>

            <programlisting> |  *PERSON_ID       |
 |  TITLE      |      |__________________|      |  AGE        |      |  *EMAIL_ADDR      |
 |_____________|                                |  FIRSTNAME  |      |___________________|
                                                |  LASTNAME   |
                                                |_____________|
 ]]></programlisting>

            <para>
                You can see that the primary key of the collection table is in fact a composite key that
                uses both columns. This also implies that there cannot be duplicate email addresses
                per person, which is exactly the semantics we need for a set in Java.
            </para>

            <para>
                You can now try to add elements to this collection, just like we did before by
                linking persons and events. It is the same code in Java:
            </para>

            <programlisting role="JAVA">

            <para>
                This time we did not use a <emphasis>fetch query to
                initialize the collection.  Monitor the SQL log and try to
                optimize this with an eager fetch.
            </para>

        </section>

        <section id="tutorial-associations-bidirectional" revision="1">
            <title>Bi-directional associations

            <para>
                Next you will map a bi-directional association.  You will make
                the association between person and event work from both sides
                in Java.  The database schema does not change, so you will still
                have many-to-many multiplicity.
            </para>

            <note>
                <para>
                    A relational database is more flexible than a network
                    programming language, in that it does not need a navigation
                    direction; data can be viewed and retrieved in any possible
                    way.
                </para>
            </note>

            <para>
                First, add a collection of participants to the
                <literal>Event class:
            </para>

            <programlisting role="JAVA">

            <para>
                Now map this side of the association in <literal>Event.hbm.xml.
            </para>

            <programlisting role="XML">
            <key column="EVENT_ID"/>
            <many-to-many column="PERSON_ID" class="Person"/>
        </set>]]>

            <para>
                These are normal <literal>set mappings in both mapping documents.
                Notice that the column names in <literal>key and many-to-many 
                swap in both mapping documents. The most important addition here is the
                <literal>inverse="true" attribute in the set element of the
                <literal>Event's collection mapping.
            </para>

            <para>
                What this means is that Hibernate should take the other side, the <literal>Person class,
                when it needs to find out information about the link between the two. This will be a lot easier to
                understand once you see how the bi-directional link between our two entities is created.
            </para>

        </section>

        <section id="tutorial-associations-usingbidir">
            <title>Working bi-directional links

            <para>
                First, keep in mind that Hibernate does not affect normal Java semantics. How did we create a
                link between a <literal>Person and an Event in the unidirectional
                example? You add an instance of <literal>Event to the collection of event references,
                of an instance of <literal>Person.  If you want to make this link
                bi-directional, you have to do the same on the other side by adding a <literal>Person
                reference to the collection in an <literal>Event. This process of "setting the link on both sides"
                is absolutely necessary with bi-directional links.
            </para>

            <para>
                Many developers program defensively and create link management methods to
                correctly set both sides (for example, in <literal>Person):
            </para>

            <programlisting role="JAVA">

            <para>
                The get and set methods for the collection are now protected. This allows classes in the
                same package and subclasses to still access the methods, but prevents everybody else from altering
                the collections directly. Repeat the steps for the collection
                on the other side.
            </para>

            <para>
                What about the <literal>inverse mapping attribute? For you, and for Java, a bi-directional
                link is simply a matter of setting the references on both sides correctly. Hibernate, however, does not
                have enough information to correctly arrange SQL <literal>INSERT and UPDATE
                statements (to avoid constraint violations). Making one side of the association <literal>inverse tells Hibernate to consider it a mirror of the other side. That is all that is necessary
                for Hibernate to resolve any issues that arise when transforming a directional navigation model to
                a SQL database schema. The rules are straightforward: all bi-directional associations
                need one side as <literal>inverse. In a one-to-many association it has to be the many-side,
                and in many-to-many association you can select either side.
            </para>

        </section>

    </section>

    <section id="tutorial-webapp">
        <title>Part 3 - The EventManager web application

        <para>
            A Hibernate web application uses <literal>Session and Transaction
            almost like a standalone application. However, some common patterns are useful. You can now write
            an <literal>EventManagerServlet. This servlet can list all events stored in the
            database, and it provides an HTML form to enter new events.
        </para>

        <section id="tutorial-webapp-servlet" revision="2">
            <title>Writing the basic servlet

            <para>
                First we need create our basic processing servlet.  Since our
                servlet only handles HTTP <literal>GET requests, we
                will only implement the <literal>doGet() method:
            </para>

            <programlisting role="JAVA">

            <para>
                Save this servlet as
                <filename>src/main/java/org/hibernate/tutorial/web/EventManagerServlet.java
            </para>

            <para>
                The pattern applied here is called <emphasis>session-per-request.
                When a request hits the servlet, a new Hibernate <literal>Session is
                opened through the first call to <literal>getCurrentSession() on the
                <literal>SessionFactory. A database transaction is then started. All
                data access occurs inside a transaction irrespective of whether the data is read or written.
                Do not use the auto-commit mode in applications.
            </para>

            <para>
                Do <emphasis>not use a new Hibernate Session for
                every database operation. Use one Hibernate <literal>Session that is
                scoped to the whole request. Use <literal>getCurrentSession(), so that
                it is automatically bound to the current Java thread.
            </para>

            <para>
                Next, the possible actions of the request are processed and the response HTML
                is rendered. We will get to that part soon.
            </para>

            <para>
                Finally, the unit of work ends when processing and rendering are complete. If any
                problems occurred during processing or rendering, an exception will be thrown
                and the database transaction rolled back. This completes the
                <literal>session-per-request pattern. Instead of the transaction
                demarcation code in every servlet, you could also write a servlet filter.
                See the Hibernate website and Wiki for more information about this pattern
                called <emphasis>Open Session in View. You will need it as soon
                as you consider rendering your view in JSP, not in a servlet.
            </para>

        </section>

        <section id="tutorial-webapp-processing" revision="1">
            <title>Processing and rendering

            <para>
                Now you can implement the processing of the request and the rendering of the page.
            </para>

<programlisting role="JAVA">Event Manager");

        // Handle actions
        if ( "store".equals(request.getParameter("action")) ) {

            String eventTitle = request.getParameter("eventTitle");
            String eventDate = request.getParameter("eventDate");

            if ( "".equals(eventTitle) || "".equals(eventDate) ) {
                out.println("<b>Please enter event title and date.");
            }
            else {
                createAndStoreEvent(eventTitle, dateFormatter.parse(eventDate));
                out.println("<b>Added event.");
            }
        }

        // Print page
       printEventForm(out);
       listEvents(out, dateFormatter);

       // Write HTML footer
       out.println("</body>");
       out.flush();
       out.close();]]></programlisting>

            <para>
                This coding style, with a mix of Java and HTML, would not scale
                in a more complex application—keep in mind that we are only illustrating
                basic Hibernate concepts in this tutorial. The code prints an HTML
                header and a footer. Inside this page, an HTML form for event entry and
                a list of all events in the database are printed. The first method is
                trivial and only outputs HTML:
            </para>

            <programlisting role="JAVA">");
        out.println("<form>");
        out.println("Title: <input name='eventTitle' length='50'/>
"); out.println("Date (e.g. 24.12.2009): <input name='eventDate' length='10'/>
"); out.println("<input type='submit' name='action' value='store'/>"); out.println("</form>"); }]]></programlisting> <para> The <literal>listEvents() method uses the Hibernate <literal>Session bound to the current thread to execute a query: </para> <programlisting role="JAVA">"); out.println("<table border='1'>"); out.println("<tr>"); out.println("<th>Event title"); out.println("<th>Event date"); out.println("</tr>"); Iterator it = result.iterator(); while (it.hasNext()) { Event event = (Event) it.next(); out.println("<tr>"); out.println("<td>" + event.getTitle() + "
... 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.