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

Hibernate example source code file (Database_Access.xml)

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

dialect, hibernate, hibernate, java, java, jdbc, proxool, sql, the, the, this, xml, xml, you

The Hibernate Database_Access.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" [
<!ENTITY % BOOK_ENTITIES SYSTEM "Hibernate_Development_Guide.ent">
%BOOK_ENTITIES;
]>
<chapter>
    <title>Database access

    <section>
        <title>Connecting
        <para>
            Hibernate connects to databases on behalf of your application. It can connect through a variety of mechanisms,
            including:
        </para>
        <itemizedlist>
            <listitem>Stand-alone built-in connection pool
            <listitem>javax.sql.DataSource
            <listitem>Two different third-party opensource JDBC connection pools:
                <itemizedlist>
                    <listitem>c3p0
                    <listitem>proxool
                </itemizedlist>
            </listitem>
        </itemizedlist>

        <note>
            <para>The built-in connection pool is not intended for production environments.
        </note>

        <!-- todo : discuss servies -->

        <section>
            <title>Configuration
            <para>
                You can configure database connections using a properties file, an XML deployment descriptor, programmatically.
      </para>
      <example>
        <title>hibernate.properties for a c3p0 connection pool
        <programlisting>
      </example>
      <example>
        <title>hibernate.cfg.xml for a connection to the bundled HSQL database
        <programlisting language="XML" role="XML">
      </example>
      <note>
        <para>
          The DTD in the configuration file used in this example is required.
        </para>
      </note>

      <section>
        <title>Programatic configuration
        <para>
          An instance of object <classname>org.hibernate.cfg.Configuration represents an entire set of
          mappings of an application's Java types to an SQL database. The
          <classname>org.hibernate.cfg.Configuration builds an immutable
          <classname>org.hibernate.SessionFactory, and compiles the mappings from various XML mapping
          files. You can specify the mapping files directly, or Hibernate can find them for you.
        </para>
        <example>
          <title>Specifying the mapping files directly
          <para>
            You can obtain a <classname>org.hibernate.cfg.Configuration instance by instantiating it
            directly and specifying XML mapping documents. If the mapping files are in the classpath, use method
            <methodname>addResource().
          </para>
          <programlisting language="Java" role="JAVA">
        </example>
        <example>
          <title>Letting Hibernate find the mapping files for you
          <para>
            The <methodname>addConfig() method directs Hibernate to search the CLASSPATH for the mapping
            files, eliminating hard-coded file names. In the following example, it searches for
            <filename>org/hibernate/auction/Item.hbm.xml and
            <filename>org/hibernate/auction/Bid.hbm.xml.
          </para>
          <programlisting language="Java" role="JAVA">
        </example>
        <example>
          <title>Specifying configuration properties
          <programlisting language="Java" role="JAVA">
        </example>
        <itemizedlist>
          <title>Other ways to configure Hibernate programmatically
          <listitem>
            <para>
              Pass an instance of <classname>java.util.Properties to
              <classname>Configuration.setProperties().
            </para>
          </listitem>
          <listitem>
            <para>
              Set System properties using <command>java
              -D<replaceable>property=value
            </para>
          </listitem>
        </itemizedlist>
      </section>
    </section>
    
    <section>
      <title>Obtaining a JDBC connection
      <para>
        After you configure the <xref linkend="hibernate-jdbc-properties" />, you can use method
        <methodname>openSession of class org.hibernate.SessionFactory to open
        sessions.  <programlisting language="Java" role="JAVA">
      </para>
      <itemizedlist id="hibernate-jdbc-properties">
        <title>Most important Hibernate JDBC properties
        <listitem>hibernate.connection.driver_class
        <listitem>hibernate.connection.url
        <listitem>hibernate.connection.username
        <listitem>hibernate.connection.password
        <listitem>hibernate.connection.pool_size
      </itemizedlist>
      <para>
        All Hibernate property names and semantics are defined in class
        <classname>org.hibernate.cfg.Environment. See the Javadoc for a complete listing.
      </para>
    </section>
  </section>
  
  <section>
    <title>Connection pooling
    <para>
      Hibernate's internal connection pooling algorithm is rudimentary, and is provided for development and testing
      purposes. Use a third-party pool for best performance and stability. To use a third-party pool, replace the
      <property>hibernate.connection.pool_size property with settings specific to your connection pool of
      choice. This disables Hibernate's internal connection pool.
    </para>
    
    <section>
      <title>c3p0 connection pool
      <para>
        C3P0 is an open source JDBC connection pool distributed along with Hibernate in the <filename>lib/
        directory. Hibernate uses its <classname>org.hibernate.connection.C3P0ConnectionProvider for
        connection pooling if you set the <property>hibernate.c3p0.* properties.  properties.
      </para>
      <itemizedlist>
        <title>Important configuration properties for the c3p0 connection pool
        <listitem>hibernate.c3p0.min_size
        <listitem>hibernate.c3p0.max_size
        <listitem>hibernate.c3p0.timeout
        <listitem>hibernate.c3p0.max_statements
      </itemizedlist>
    </section>
    
    <section>
      <title>Proxool connection pool
      <para>
        Proxool is another open source JDBC connection pool distributed along with Hibernate in the
        <filename>lib/ directory. Hibernate uses its
        <classname>org.hibernate.connection.ProxoolConnectionProvider for connection pooling if you set the
        <property>hibernate.proxool.* properties. Unlike c3p0, proxool requires some additional configuration
        parameters, as described by the Proxool documentation available at <ulink
        url="http://proxool.sourceforge.net/configure.html" />.
      </para>
      <table>
        <title>Important configuration properties for the Proxool connection pool
        <tgroup cols="2">
          <colspec colwidth="120px" />
          <colspec colwidth="320px" />
          <thead>
            <row>
              <entry>Property
              <entry>Description
            </row>
          </thead>
          <tbody>
            <row>
              <entry>hibernate.proxool.xml
              <entry>Configure Proxool provider using an XML file (.xml is appended automatically)
            </row>
            <row>
              <entry>hibernate.proxool.properties
              <entry>Configure the Proxool provider using a properties file (.properties is appended
              automatically)</entry>
            </row>
            <row>
              <entry>hibernate.proxool.existing_pool
              <entry>Whether to configure the Proxool provider from an existing pool
            </row>
            <row>
              <entry>hibernate.proxool.pool_alias
              <entry>Proxool pool alias to use. Required.
            </row>
          </tbody>
        </tgroup>
      </table>
    </section>

    
    <section>
      <title>Obtaining connections from an application server, using JNDI
      <para>
        To use Hibernate inside an application server, configure Hibernate to obtain connections from an application
        server <classname>javax.sql.Datasource registered in JNDI, by setting at least one of the following
        properties:
      </para>
      <itemizedlist>
        <title>Important Hibernate properties for JNDI datasources
        <listitem>hibernate.connection.datasource (required)
        <listitem>hibernate.jndi.url
        <listitem>hibernate.jndi.class
        <listitem>hibernate.connection.username
        <listitem>hibernate.connection.password
      </itemizedlist>
      <para>
        JDBC connections obtained from a JNDI datasource automatically participate in the container-managed transactions
        of the application server.
      </para>
    </section>
    
    <section>
      <title>Other connection-specific configuration
      <para>
        You can pass arbitrary connection properties by prepending <literal>hibernate.connection to the
        connection property name. For example, specify a charSet connection property as
        <property>hibernate.connection.charSet.
      </para>
      <para>
        You can define your own plugin strategy for obtaining JDBC connections by implementing the interface
        <interfacename>org.hibernate.connection.ConnectionProvider and specifying your custom
        implementation with the <property>hibernate.connection.provider_class property.
      </para>
    </section>
    
    <section>
      <title>Optional configuration properties
      <para>
        In addition to the properties mentioned in the previous sections, Hibernate includes many other optional
        properties. See <xref linkend="appendix-Configuration_Properties" /> for a more complete list.
      </para>
    </section>
  </section>
  
  <section id="configuring-dialects">
    <title>Dialects
    <para>
        Although SQL is relatively standardized, each database vendor uses a subset of supported syntax. This is referred
        to as a <firstterm>dialect.  Hibernate handles variations across these dialects through its
        <classname>org.hibernate.dialect.Dialect class and the various subclasses for each vendor dialect.
    </para>

    <table>
      <title>Supported database dialects
      <tgroup cols="2">
        <colspec colwidth="120px" />
        <colspec colwidth="320px" />
        <thead>
          <row>
            <entry>Database
            <entry>Dialect
          </row>
        </thead>
        <tbody>
          <row>
            <entry>DB2
            <entry>org.hibernate.dialect.DB2Dialect
          </row>
          <row>
            <entry>DB2 AS/400
            <entry>org.hibernate.dialect.DB2400Dialect
          </row>
          <row>
            <entry>DB2 OS390
            <entry>org.hibernate.dialect.DB2390Dialect
          </row>
          <row>
            <entry>Firebird
            <entry>org.hibernate.dialect.FirebirdDialect
          </row>
          <row>
            <entry>FrontBase
            <entry>org.hibernate.dialect.FrontbaseDialect
          </row>
          <row>
            <entry>HypersonicSQL
            <entry>org.hibernate.dialect.HSQLDialect
          </row>
          <row>
            <entry>Informix
            <entry>org.hibernate.dialect.InformixDialect
          </row>
          <row>
            <entry>Interbase
            <entry>org.hibernate.dialect.InterbaseDialect
          </row>
          <row>
            <entry>Ingres
            <entry>org.hibernate.dialect.IngresDialect
          </row>
          <row>
            <entry>Microsoft SQL Server
            <entry>org.hibernate.dialect.SQLServerDialect
          </row>
          <row>
            <entry>Mckoi SQL
            <entry>org.hibernate.dialect.MckoiDialect
          </row>
          <row>
            <entry>MySQL
            <entry>org.hibernate.dialect.MySQLDialect
          </row>
          <row>
            <entry>MySQL with InnoDB
            <entry>org.hibernate.dialect.MySQLInnoDBDialect
          </row>
          <row>
            <entry>MySQL with MyISAM
            <entry>org.hibernate.dialect.MySQLMyISAMDialect
          </row>
          <row>
            <entry>Oracle 8i
            <entry>org.hibernate.dialect.Oracle8iDialect
          </row>
          <row>
            <entry>Oracle 9i
            <entry>org.hibernate.dialect.Oracle9iDialect
          </row>
          <row>
            <entry>Oracle 10g
            <entry>org.hibernate.dialect.Oracle10gDialect
          </row>
          <row>
            <entry>Pointbase
            <entry>org.hibernate.dialect.PointbaseDialect
          </row>
          <row>
            <entry>PostgreSQL
            <entry>org.hibernate.dialect.PostgreSQLDialect
          </row>
          <row>
            <entry>Progress
            <entry>org.hibernate.dialect.ProgressDialect
          </row>
          <row>
            <entry>SAP DB
            <entry>org.hibernate.dialect.SAPDBDialect
          </row>
          <row>
            <entry>Sybase
            <entry>org.hibernate.dialect.SybaseDialect
          </row>
          <row>
            <entry>Sybase Anywhere
            <entry>org.hibernate.dialect.SybaseAnywhereDialect
          </row>
        </tbody>
      </tgroup>
    </table>

      <section>
          <title>Specifying the Dialect to use
          <para>
              The developer may manually specify the Dialect to use by setting the
              <property>hibernate.dialect configuration property to the name of a specific
              <classname>org.hibernate.dialect.Dialect class to use.
          </para>
      </section>

      <section>
          <title>Dialect resolution
          <para>
              Assuming a <interfacename>org.hibernate.connection.ConnectionProvider has been
              set up, Hibernate will attempt to automatically determine the Dialect to use based on the
              <interfacename>java.sql.DatabaseMetaData reported by a
              <interfacename>java.sql.Connection obtained from that
              <interfacename>org.hibernate.connection.ConnectionProvider.
          </para>
          <para>
                This functionality is provided by a series of
                <interfacename>org.hibernate.dialect.resolver.DialectResolver instances registered
                with Hibernate internally.  Hibernate comes with a standard set of recognitions.  If your application
                requires extra Dialect resolution capabilities, it would simply register a custom implementation
                of <interfacename>org.hibernate.dialect.resolver.DialectResolver as follows:
          </para>
          <!-- document an example using the service registry -->
            <para>
                Registered <interfacename>org.hibernate.dialect.resolver.DialectResolver are
                <emphasis>prepended to an internal list of resolvers, so they take precedence
                before any already registered resolvers including the standard one.
            </para>
      </section>
  </section>

  <section>
    <title>Automatic schema generation with SchemaExport
    <para>
      SchemaExport is a Hibernate utility which generates DDL from your mapping files. The generated schema includes
      referential integrity constraints, primary and foreign keys, for entity and collection tables. It also creates
      tables and sequences for mapped identifier generators.
    </para>
    <note>
      <para>
        You must specify a SQL Dialect via the <property>hibernate.dialect property when using this tool,
        because DDL is highly vendor-specific. See <xref linkend="configuring-dialects" /> for information.
      </para>
    </note>
    <para>
      Before Hibernate can generate your schema, you must customize your mapping files.
    </para>
    
    <section>
      <title>Customizing the mapping files
      <para>
        Hibernate provides several elements and attributes to customize your mapping files. They are listed in <xref
        linkend="tab-customizing-schema" />, and a logical order of customization is presented in <xref
        linkend="proc-customizing-schema" />.
      </para>
      <table id="tab-customizing-schema">
        <title>Elements and attributes provided for customizing mapping files
        <tgroup cols="3">
          <colspec colwidth="80px" />
          <colspec colwidth="80px" />
          <colspec colwidth="280px" />
          <thead>
            <row>
              <entry>Name
              <entry>Type of value
              <entry>Description
            </row>
          </thead>
          <tbody>
            <row>
              <entry>length
              <entry>number
              <entry>Column length
            </row>
            <row>
              <entry>precision
              <entry>number
              <entry>Decimal precision of column
            </row>
            <row>
              <entry>scale
              <entry>number
              <entry>Decimal scale of column
            </row>
            <row>
              <entry>not-null
              <entry>true or false
              <entry>Whether a column is allowed to hold null values
            </row>
            <row>
              <entry>unique
              <entry>true or false
              <entry>Whether values in the column must be unique
            </row>
            <row>
              <entry>index
              <entry>string
              <entry>The name of a multi-column index
            </row>
            <row>
              <entry>unique-key
              <entry>string
              <entry>The name of a multi-column unique constraint
            </row>
            <row>
              <entry>foreign-key
              <entry>string
              <entry>The name of the foreign key constraint generated for an association. This applies to
              <one-to-one>, <many-to-one>, <key>, and <many-to-many> mapping
              elements. <literal>inverse="true" sides are skipped by SchemaExport.
            </row>
            <row>
              <entry>sql-type
              <entry>string
              <entry>Overrides the default column type. This applies to the <column> element only.
            </row>
            <row>
              <entry>default
              <entry>string
              <entry>Default value for the column
            </row>
            <row>
              <entry>check
              <entry>string
              <entry>An SQL check constraint on either a column or atable
            </row>
          </tbody>
        </tgroup>
      </table>
      <procedure id="proc-customizing-schema">
        <title>Customizing the schema
        <step>
          <title>Set the length, precision, and scale of mapping elements.
          <para>
            Many Hibernate mapping elements define optional attributes named <option>length,
            <option>precision, and .
          </para>
          <programlisting language="XML" role="XML">
        </step>
        <step>
          <title>Set the , ,  attributes.
          <para>
            The <option>not-null and  attributes generate constraints on table columns.
          </para>
          <para>
            The unique-key attribute groups columns in a single, unique key constraint. Currently, the specified value
            of the unique-key attribute does not name the constraint in the generated DDL. It only groups the columns in
            the mapping file.
          </para>
          <programlisting language="XML" role="XML">
        </step>
        <step>
          <title>Set the  and  attributes.
          <para>
            The <option>index attribute specifies the name of an index for Hibernate to create using the mapped
            column or columns. You can group multiple columns into the same index by assigning them the same index name.
          </para>
          <para>
            A foreign-key attribute overrides the name of any generated foreign key constraint.
          </para>
          <programlisting language="XML" role="XML">
        </step>
        <step>
          <title>Set child  elements.
          <para>
            Many mapping elements accept one or more child <column> elements. This is particularly useful for
            mapping types involving multiple columns.
          </para>
          <programlisting language="XML" role="XML">
        </step>
        <step>
          <title>Set the  attribute.
          <para>
            The <option>default attribute represents a default value for a column. Assign the same value to the
            mapped property before saving a new instance of the mapped class.
          </para>
          <programlisting language="XML" role="XML">
        </step>
        <step>
          <title>Set the  attribure.
          <para>
            Use the <option>sql-type attribute to override the default mapping of a Hibernate type to SQL
            datatype.
          </para>
          <programlisting language="XML" role="XML">
        </step>
        <step>
          <title>Set the  attribute.
          <para>
            use the <option>check attribute to specify a check constraint.
          </para>
          <programlisting language="XML" role="XML">
        </step>
        <step>
          <title>Add <comment> elements to your schema.
          <para>
            Use the <comment> element to specify comments for the generated schema.
          </para>
          <programlisting language="XML" role="XML">
        </step>
      </procedure>
    </section>

    <section>
      <title>Running the SchemaExport tool
      <para>
        The SchemaExport tool writes a DDL script to standard output, executes the DDL statements, or both.
      </para>
      <example>
        <title>SchemaExport syntax
        <screen>
          java -cp hibernate_classpaths org.hibernate.tool.hbm2ddl.SchemaExport <replaceable>options mapping_files 
        </screen>
      </example>
      <table>
        <title>SchemaExport Options
        <tgroup cols="2">
          <colspec colwidth="120px" />
          <colspec colwidth="320px" />
          <thead>
            <row>
              <entry>Option
              <entry>Description
            </row>
          </thead>
          <tbody>
            <row>
              <entry>--quiet
              <entry>do not output the script to standard output
            </row>
            <row>
              <entry>--drop
              <entry>only drop the tables
            </row>
            <row>
              <entry>--create
              <entry>only create the tables
            </row>
            <row>
              <entry>--text
              <entry>do not export to the database
            </row>
            <row>
              <entry>--output=my_schema.ddl
              <entry>output the ddl script to a file
            </row>
            <row>
              <entry>--naming=eg.MyNamingStrategy
              <entry>select a NamingStrategy
            </row>
            <row>
              <entry>--config=hibernate.cfg.xml
              <entry>read Hibernate configuration from an XML file
            </row>
            <row>
              <entry>--properties=hibernate.properties
              <entry>read database properties from a file
            </row>
            <row>
              <entry>--format
              <entry>format the generated SQL nicely in the script
            </row>
            <row>
              <entry>--delimiter=;
              <entry>set an end-of-line delimiter for the script
            </row>
          </tbody>
        </tgroup>
      </table>
      <example>
        <title>Embedding SchemaExport into your application
        <programlisting language="Java" role="JAVA">
      </example>
    </section>
  </section>
</chapter>

Other Hibernate examples (source code examples)

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