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

Hibernate example source code file (configuration.xml)

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

configuration, for, hibernate, hibernate, java, jdbc, jdbc, jndi, jndi, jta, sql, this, this, xml

The Hibernate configuration.xml source code

<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
  ~ indicated by the @author tags or express copyright attribution
  ~ statements applied by the authors.  All third-party contributions are
  ~ distributed under license by Red Hat Middleware LLC.
  ~
  ~ This copyrighted material is made available to anyone wishing to use, modify,
  ~ copy, or redistribute it subject to the terms and conditions of the GNU
  ~ Lesser General Public License, as published by the Free Software Foundation.
  ~
  ~ This program is distributed in the hope that it will be useful,
  ~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  ~ or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
  ~ for more details.
  ~
  ~ You should have received a copy of the GNU Lesser General Public License
  ~ along with this distribution; if not, write to:
  ~ Free Software Foundation, Inc.
  ~ 51 Franklin Street, Fifth Floor
  ~ Boston, MA  02110-1301  USA
  -->
<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
"http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
<!ENTITY % BOOK_ENTITIES SYSTEM "../HIBERNATE_-_Relational_Persistence_for_Idiomatic_Java.ent">
%BOOK_ENTITIES;
]>
<chapter id="session-configuration" revision="1">
  <title>Configuration

  <para>Hibernate is designed to operate in many different environments and,
  as such, there is a broad range of configuration parameters. Fortunately,
  most have sensible default values and Hibernate is distributed with an
  example <literal>hibernate.properties file in
  <literal>etc/ that displays the various options. Simply put the
  example file in your classpath and customize it to suit your needs.</para>

  <section id="configuration-programmatic" revision="1">
    <title>Programmatic configuration

    <para>An instance of
    <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 is used to
    build an immutable
    <interfacename>org.hibernate.SessionFactory. The mappings
    are compiled from various XML mapping files.</para>

    <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 <literal>addResource().
    For example:</para>

    <programlisting role="JAVA">Configuration cfg = new Configuration()
    .addResource("Item.hbm.xml")
    .addResource("Bid.hbm.xml");</programlisting>

    <para>An alternative way is to specify the mapped class and allow
    Hibernate to find the mapping document for you:</para>

    <programlisting role="JAVA">Configuration cfg = new Configuration()
    .addClass(org.hibernate.auction.Item.class)
    .addClass(org.hibernate.auction.Bid.class);</programlisting>

    <para>Hibernate will then search for mapping files named
    <filename>/org/hibernate/auction/Item.hbm.xml and
    <filename>/org/hibernate/auction/Bid.hbm.xml in the classpath.
    This approach eliminates any hardcoded filenames.</para>

    <para>A org.hibernate.cfg.Configuration also allows
    you to specify configuration properties. For example:</para>

    <programlisting role="JAVA">Configuration cfg = new Configuration()
    .addClass(org.hibernate.auction.Item.class)
    .addClass(org.hibernate.auction.Bid.class)
    .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect")
    .setProperty("hibernate.connection.datasource", "java:comp/env/jdbc/test")
    .setProperty("hibernate.order_updates", "true");</programlisting>

    <para>This is not the only way to pass configuration properties to
    Hibernate. Some alternative options include:</para>

    <orderedlist spacing="compact">
      <listitem>
        <para>Pass an instance of java.util.Properties
        to <literal>Configuration.setProperties().
      </listitem>

      <listitem>
        <para>Place a file named hibernate.properties in
        a root directory of the classpath.</para>
      </listitem>

      <listitem>
        <para>Set System properties using java
        -Dproperty=value</literal>.
      </listitem>

      <listitem>
        <para>Include <property> elements in
        <literal>hibernate.cfg.xml (this is discussed later).
      </listitem>
    </orderedlist>

    <para>If you want to get started
    quickly<filename>hibernate.properties is the easiest
    approach.</para>

    <para>The org.hibernate.cfg.Configuration is
    intended as a startup-time object that will be discarded once a
    <literal>SessionFactory is created.
  </section>

  <section id="configuration-sessionfactory">
    <title>Obtaining a SessionFactory

    <para>When all mappings have been parsed by the
    <classname>org.hibernate.cfg.Configuration, the application
    must obtain a factory for
    <interfacename>org.hibernate.Session instances. This
    factory is intended to be shared by all application threads:</para>

    <programlisting role="JAVA">SessionFactory sessions = cfg.buildSessionFactory();

    <para>Hibernate does allow your application to instantiate more than one
    <interfacename>org.hibernate.SessionFactory. This is
    useful if you are using more than one database.</para>
  </section>

  <section id="configuration-hibernatejdbc" revision="1">
    <title>JDBC connections

    <para>It is advisable to have the
    <interfacename>org.hibernate.SessionFactory create and
    pool JDBC connections for you. If you take this approach, opening a
    <interfacename>org.hibernate.Session is as simple
    as:</para>

    <programlisting role="JAVA">Session session = sessions.openSession(); // open a new Session

    <para>Once you start a task that requires access to the database, a JDBC
    connection will be obtained from the pool.</para>

    <para>Before you can do this, you first need to pass some JDBC connection
    properties to Hibernate. All Hibernate property names and semantics are
    defined on the class <classname>org.hibernate.cfg.Environment.
    The most important settings for JDBC connection configuration are outlined
    below.</para>

    <para>Hibernate will obtain and pool connections using
    <classname>java.sql.DriverManager if you set the following
    properties:</para>

    <table frame="topbot">
      <title>Hibernate JDBC Properties

      <tgroup cols="2">
        <colspec colname="c1" colwidth="1*" />

        <colspec colname="c2" colwidth="1*" />

        <thead>
          <row>
            <entry>Property name

            <entry>Purpose
          </row>
        </thead>

        <tbody>
          <row>
            <entry>hibernate.connection.driver_class

            <entry>JDBC driver class
          </row>

          <row>
            <entry>hibernate.connection.url

            <entry>JDBC URL
          </row>

          <row>
            <entry>hibernate.connection.username

            <entry>database user
          </row>

          <row>
            <entry>hibernate.connection.password

            <entry>database user password
          </row>

          <row>
            <entry>hibernate.connection.pool_size

            <entry>maximum number of pooled
            connections</emphasis>
          </row>
        </tbody>
      </tgroup>
    </table>

    <para>Hibernate's own connection pooling algorithm is, however, quite
    rudimentary. It is intended to help you get started and is <emphasis>not
    intended for use in a production system</emphasis>, or even for
    performance testing. You should use a third party pool for best
    performance and stability. Just replace the
    <property>hibernate.connection.pool_size property with
    connection pool specific settings. This will turn off Hibernate's internal
    pool. For example, you might like to use c3p0.</para>

    <para>C3P0 is an open source JDBC connection pool distributed along with
    Hibernate in the <filename>lib directory. Hibernate will use
    its <classname>org.hibernate.connection.C3P0ConnectionProvider
    for connection pooling if you set <property>hibernate.c3p0.*
    properties. If you would like to use Proxool, refer to the packaged
    <filename>hibernate.properties and the Hibernate web site for
    more information.</para>

    <para>The following is an example
    <filename>hibernate.properties file for c3p0:

    <programlisting>hibernate.connection.driver_class = org.postgresql.Driver
hibernate.connection.url = jdbc:postgresql://localhost/mydatabase
hibernate.connection.username = myuser
hibernate.connection.password = secret
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=50
hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect</programlisting>

    <para>For use inside an application server, you should almost always
    configure Hibernate to obtain connections from an application server
    <interfacename>javax.sql.Datasource registered in JNDI.
    You will need to set at least one of the following properties:</para>

    <table frame="topbot">
      <title>Hibernate Datasource Properties

      <tgroup cols="2">
        <colspec colname="c1" colwidth="1*" />

        <colspec colname="c2" colwidth="1*" />

        <thead>
          <row>
            <entry>Property name

            <entry>Purpose
          </row>
        </thead>

        <tbody>
          <row>
            <entry>hibernate.connection.datasource

            <entry>datasource JNDI name
          </row>

          <row>
            <entry>hibernate.jndi.url

            <entry>URL of the JNDI provider
            (optional)</entry>
          </row>

          <row>
            <entry>hibernate.jndi.class

            <entry>class of the JNDI
            <literal>InitialContextFactory
            (optional)</entry>
          </row>

          <row>
            <entry>hibernate.connection.username

            <entry>database user (optional)
          </row>

          <row>
            <entry>hibernate.connection.password

            <entry>database user password
            (optional)</entry>
          </row>
        </tbody>
      </tgroup>
    </table>

    <para>Here is an example hibernate.properties file
    for an application server provided JNDI datasource:</para>

    <programlisting>hibernate.connection.datasource = java:/comp/env/jdbc/test
hibernate.transaction.factory_class = \
    org.hibernate.transaction.JTATransactionFactory
hibernate.transaction.manager_lookup_class = \
    org.hibernate.transaction.JBossTransactionManagerLookup
hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect</programlisting>

    <para>JDBC connections obtained from a JNDI datasource will automatically
    participate in the container-managed transactions of the application
    server.</para>

    <para>Arbitrary connection properties can be given by prepending
    "<literal>hibernate.connection" to the connection property name.
    For example, you can specify a <property>charSet connection
    property using <property>hibernate.connection.charSet.

    <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 via the
    <property>hibernate.connection.provider_class property.
  </section>

  <section id="configuration-optional" revision="1">
    <title>Optional configuration properties

    <para>There are a number of other properties that control the behavior of
    Hibernate at runtime. All are optional and have reasonable default
    values.</para>

    <para>
        <para>Some of these properties are "system-level"
        only.</emphasis> System-level properties can be set only via
        <literal>java -Dproperty=value or
        <filename>hibernate.properties. They
        <emphasis>cannot be set by the other techniques described
        above.</para>
      </warning>

    <table frame="topbot" id="configuration-optional-properties" revision="8">
      <title>Hibernate Configuration Properties

      <tgroup cols="2">
        <colspec colname="c1" colwidth="1*" />

        <colspec colname="c2" colwidth="1*" />

        <thead>
          <row>
            <entry>Property name

            <entry>Purpose
          </row>
        </thead>

        <tbody>
          <row>
            <entry>hibernate.dialect

            <entry>The classname of a Hibernate
            <classname>org.hibernate.dialect.Dialect which allows
            Hibernate to generate SQL optimized for a particular relational
            database. <para> e.g.
            <literal>full.classname.of.Dialect   In
            most cases Hibernate will actually be able to choose the correct
            <classname>org.hibernate.dialect.Dialect
            implementation based on the <literal>JDBC metadata
            returned by the JDBC driver. </para>
          </row>

          <row>
            <entry>hibernate.show_sql

            <entry>Write all SQL statements to console. This is an alternative
            to setting the log category <literal>org.hibernate.SQL
            to <literal>debug.   true |
            <literal>false 
          </row>

          <row>
            <entry>hibernate.format_sql

            <entry>Pretty print the SQL in the log and console. 
            <emphasis role="strong">e.g. true |
            <literal>false 
          </row>

          <row>
            <entry>hibernate.default_schema

            <entry>Qualify unqualified table names with the given
            schema/tablespace in generated SQL. <para>  SCHEMA_NAME
            </para>
          </row>

          <row>
            <entry>hibernate.default_catalog

            <entry>Qualifies unqualified table names with the given catalog in
            generated SQL. <para> e.g.
            <literal>CATALOG_NAME 
          </row>

          <row>
            <entry>hibernate.session_factory_name

            <entry>The
            <interfacename>org.hibernate.SessionFactory will
            be automatically bound to this name in JNDI after it has been
            created. <para> e.g.
            <literal>jndi/composite/name 
          </row>

          <row>
            <entry>hibernate.max_fetch_depth

            <entry>Sets a maximum "depth" for the outer join fetch tree for
            single-ended associations (one-to-one, many-to-one). A
            <literal>0 disables default outer join fetching. 
            <emphasis role="strong">e.g. recommended values between
            <literal>0 and 3 
          </row>

          <row>
            <entry>hibernate.default_batch_fetch_size

            <entry>Sets a default size for Hibernate batch fetching of
            associations. <para> e.g.
            recommended values <literal>4, 8,
            <literal>16 
          </row>

          <row>
            <entry>hibernate.default_entity_mode

            <entry>Sets a default mode for entity representation for all
            sessions opened from this <literal>SessionFactory 
            <literal>dynamic-map, dom4j,
            <literal>pojo 
          </row>

          <row>
            <entry>hibernate.order_updates

            <entry>Forces Hibernate to order SQL updates by the primary key
            value of the items being updated. This will result in fewer
            transaction deadlocks in highly concurrent systems. <para>
            <emphasis role="strong">e.g. true |
            <literal>false 
          </row>

          <row>
            <entry>hibernate.generate_statistics

            <entry>If enabled, Hibernate will collect statistics useful for
            performance tuning. <para> e.g.
            <literal>true | false 
          </row>

          <row>
            <entry>hibernate.use_identifier_rollback

            <entry>If enabled, generated identifier properties will be reset
            to default values when objects are deleted. <para>  true |
            <literal>false 
          </row>

          <row>
            <entry>hibernate.use_sql_comments

            <entry>If turned on, Hibernate will generate comments inside the
            SQL, for easier debugging, defaults to <literal>false.
            <para> e.g.
            <literal>true | false 
          </row>

          <row>
            <entry>hibernate.id.new_generator_mappings

            <entry>Setting is relevant when using
            <classname>@GeneratedValue. It indicates whether or
            not the new <classname>IdentifierGenerator
            implementations are used for
            <classname>javax.persistence.GenerationType.AUTO,
            <classname>javax.persistence.GenerationType.TABLE and
            <classname>javax.persistence.GenerationType.SEQUENCE.
            Default to <literal>false to keep backward
            compatibility. <para> e.g.
            <literal>true | false 
          </row>
        </tbody>
      </tgroup>
    </table>

    <note>
      <para>We recommend all new projects which make use of to use
      <classname>@GeneratedValue to also set
      <code>hibernate.id.new_generator_mappings=true as the new
      generators are more efficient and closer to the JPA 2 specification
      semantic. However they are not backward compatible with existing
      databases (if a sequence or a table is used for id generation).</para>
    </note>

    <table frame="topbot" id="configuration-jdbc-properties" revision="8">
      <title>Hibernate JDBC and Connection Properties

      <tgroup cols="2">
        <!--
                <colspec colname="c1" colwidth="1*"/>
                <colspec colname="c2" colwidth="1*"/>
-->

        <thead>
          <row>
            <entry>Property name

            <entry>Purpose
          </row>
        </thead>

        <tbody>
          <row>
            <entry>hibernate.jdbc.fetch_size

            <entry>A non-zero value determines the JDBC fetch size (calls
            <literal>Statement.setFetchSize()).
          </row>

          <row>
            <entry>hibernate.jdbc.batch_size

            <entry>A non-zero value enables use of JDBC2 batch updates by
            Hibernate. <para> e.g.
            recommended values between <literal>5 and
            <literal>30 
          </row>

          <row>
            <entry>hibernate.jdbc.batch_versioned_data

            <entry>Set this property to true if your JDBC
            driver returns correct row counts from
            <literal>executeBatch(). It is usually safe to turn this
            option on. Hibernate will then use batched DML for automatically
            versioned data. Defaults to <literal>false. 
            <emphasis role="strong">e.g. true |
            <literal>false 
          </row>

          <row>
            <entry>hibernate.jdbc.factory_class

            <entry>Select a custom
            <interfacename>org.hibernate.jdbc.Batcher. Most
            applications will not need this configuration property. <para>
            <emphasis role="strong">e.g.
            <literal>classname.of.BatcherFactory 
          </row>

          <row>
            <entry>hibernate.jdbc.use_scrollable_resultset

            <entry>Enables use of JDBC2 scrollable resultsets by Hibernate.
            This property is only necessary when using user-supplied JDBC
            connections. Hibernate uses connection metadata otherwise. <para>
            <emphasis role="strong">e.g. true |
            <literal>false 
          </row>

          <row>
            <entry>hibernate.jdbc.use_streams_for_binary

            <entry>Use streams when writing/reading binary
            or <literal>serializable types to/from JDBC.
            <emphasis>*system-level property*   true |
            <literal>false 
          </row>

          <row>
            <entry>hibernate.jdbc.use_get_generated_keys

            <entry>Enables use of JDBC3
            <literal>PreparedStatement.getGeneratedKeys() to
            retrieve natively generated keys after insert. Requires JDBC3+
            driver and JRE1.4+, set to false if your driver has problems with
            the Hibernate identifier generators. By default, it tries to
            determine the driver capabilities using connection metadata.
            <para> e.g.
            <literal>true|false 
          </row>

          <row>
            <entry>hibernate.connection.provider_class

            <entry>The classname of a custom
            <interfacename>org.hibernate.connection.ConnectionProvider
            which provides JDBC connections to Hibernate. <para> 
            <literal>classname.of.ConnectionProvider 
          </row>

          <row>
            <entry>hibernate.connection.isolation

            <entry>Sets the JDBC transaction isolation level. Check
            <interfacename>java.sql.Connection for meaningful
            values, but note that most databases do not support all isolation
            levels and some define additional, non-standard isolations. <para>
            <emphasis role="strong">e.g. 1, 2, 4,
            8</literal> 
          </row>

          <row>
            <entry>hibernate.connection.autocommit

            <entry>Enables autocommit for JDBC pooled connections (it is not
            recommended). <para> e.g.
            <literal>true | false 
          </row>

          <row>
            <entry>hibernate.connection.release_mode

            <entry>Specifies when Hibernate should release JDBC connections.
            By default, a JDBC connection is held until the session is
            explicitly closed or disconnected. For an application server JTA
            datasource, use <literal>after_statement to aggressively
            release connections after every JDBC call. For a non-JTA
            connection, it often makes sense to release the connection at the
            end of each transaction, by using
            <literal>after_transaction. auto will
            choose <literal>after_statement for the JTA and CMT
            transaction strategies and <literal>after_transaction
            for the JDBC transaction strategy. <para>  auto (default) |
            <literal>on_close | after_transaction
            | <literal>after_statement   This setting
            only affects <literal>Sessions returned from
            <literal>SessionFactory.openSession. For
            <literal>Sessions obtained through
            <literal>SessionFactory.getCurrentSession, the
            <literal>CurrentSessionContext implementation configured
            for use controls the connection release mode for those
            <literal>Sessions. See 
          </row>

          <row>
            <entry>hibernate.connection.<propertyName>

            <entry>Pass the JDBC property
            <emphasis><propertyName> to
            <literal>DriverManager.getConnection().
          </row>

          <row>
            <entry>hibernate.jndi.<propertyName>

            <entry>Pass the property <propertyName>
            to the JNDI <literal>InitialContextFactory.
          </row>
        </tbody>
      </tgroup>
    </table>

    <table frame="topbot" id="configuration-cache-properties" revision="7">
      <title>Hibernate Cache Properties

      <tgroup cols="2">
        <colspec colname="c1" colwidth="1*" />

        <colspec colname="c2" colwidth="1*" />

        <thead>
          <row>
            <entry>Property name

            <entry>Purpose
          </row>
        </thead>

        <tbody>
          <row>
            <entry>hibernate.cache.provider_class

            <entry>The classname of a custom CacheProvider.
            <para> e.g.
            <literal>classname.of.CacheProvider 
          </row>

          <row>
            <entry>hibernate.cache.use_minimal_puts

            <entry>Optimizes second-level cache operation to minimize writes,
            at the cost of more frequent reads. This setting is most useful
            for clustered caches and, in Hibernate3, is enabled by default for
            clustered cache implementations. <para>  true|false
            </para>
          </row>

          <row>
            <entry>hibernate.cache.use_query_cache

            <entry>Enables the query cache. Individual queries still have to
            be set cachable. <para> e.g.
            <literal>true|false 
          </row>

          <row>
            <entry>hibernate.cache.use_second_level_cache

            <entry>Can be used to completely disable the second level cache,
            which is enabled by default for classes which specify a
            <literal><cache> mapping.   true|false
            </para>
          </row>

          <row>
            <entry>hibernate.cache.query_cache_factory

            <entry>The classname of a custom QueryCache
            interface, defaults to the built-in
            <literal>StandardQueryCache.  
            <literal>classname.of.QueryCache 
          </row>

          <row>
            <entry>hibernate.cache.region_prefix

            <entry>A prefix to use for second-level cache region names. 
            <emphasis role="strong">e.g. prefix
            </para>
          </row>

          <row>
            <entry>hibernate.cache.use_structured_entries

            <entry>Forces Hibernate to store data in the second-level cache in
            a more human-friendly format. <para>  true|false
            </para>
          </row>

          <row>
            <entry>hibernate.cache.default_cache_concurrency_strategy

            <entry>Setting used to give the name of the default
            <classname>org.hibernate.annotations.CacheConcurrencyStrategy
            to use when either <classname>@Cacheable or
            <classname>@Cache is used.
            <code>@Cache(strategy="..") is used to override this
            default.</entry>
          </row>
        </tbody>
      </tgroup>
    </table>

    <table frame="topbot" id="configuration-transaction-properties"
           revision="9">
      <title>Hibernate Transaction Properties

      <tgroup cols="2">
        <colspec colname="c1" colwidth="1*" />

        <colspec colname="c2" colwidth="1*" />

        <thead>
          <row>
            <entry>Property name

            <entry>Purpose
          </row>
        </thead>

        <tbody>
          <row>
            <entry>hibernate.transaction.factory_class

            <entry>The classname of a TransactionFactory to
            use with Hibernate <literal>Transaction API (defaults to
            <literal>JDBCTransactionFactory).  
            <literal>classname.of.TransactionFactory 
          </row>

          <row>
            <entry>jta.UserTransaction

            <entry>A JNDI name used by
            <literal>JTATransactionFactory to obtain the JTA
            <literal>UserTransaction from the application server.
            <para> e.g.
            <literal>jndi/composite/name 
          </row>

          <row>
            <entry>hibernate.transaction.manager_lookup_class

            <entry>The classname of a
            <literal>TransactionManagerLookup. It is required when
            JVM-level caching is enabled or when using hilo generator in a JTA
            environment. <para> e.g.
            <literal>classname.of.TransactionManagerLookup
            </para>
          </row>

          <row>
            <entry>hibernate.transaction.flush_before_completion

            <entry>If enabled, the session will be automatically flushed
            during the before completion phase of the transaction. Built-in
            and automatic session context management is preferred, see <xref
            linkend="architecture-current-session" />. <para>  true |
            <literal>false 
          </row>

          <row>
            <entry>hibernate.transaction.auto_close_session

            <entry>If enabled, the session will be automatically closed during
            the after completion phase of the transaction. Built-in and
            automatic session context management is preferred, see <xref
            linkend="architecture-current-session" />. <para>  true |
            <literal>false 
          </row>
        </tbody>
      </tgroup>
    </table>

    <table frame="topbot" id="configuration-misc-properties" revision="11">
      <title>Miscellaneous Properties

      <tgroup cols="2">
        <colspec colname="c1" colwidth="1*" />

        <colspec colname="c2" colwidth="1*" />

        <thead>
          <row>
            <entry>Property name

            <entry>Purpose
          </row>
        </thead>

        <tbody>
          <row>
            <entry>hibernate.current_session_context_class

            <entry>Supply a custom strategy for the scoping of the "current"
            <literal>Session. See  jta |
            <literal>thread | managed |
            <literal>custom.Class 
          </row>

          <row>
            <entry>hibernate.query.factory_class

            <entry>Chooses the HQL parser implementation.  
            <literal>org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory
            or
            <literal>org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory
            </para>
          </row>

          <row>
            <entry>hibernate.query.substitutions

            <entry>Is used to map from tokens in Hibernate queries to SQL
            tokens (tokens might be function or literal names, for example).
            <para> e.g.
            <literal>hqlLiteral=SQL_LITERAL, hqlFunction=SQLFUNC
            </para>
          </row>

          <row>
            <entry>hibernate.hbm2ddl.auto

            <entry>Automatically validates or exports schema DDL to the
            database when the <literal>SessionFactory is created.
            With <literal>create-drop, the database schema will be
            dropped when the <literal>SessionFactory is closed
            explicitly. <para> e.g.
            <literal>validate | update |
            <literal>create | create-drop
            </para>
          </row>

          <row>
            <entry>hibernate.hbm2ddl.import_files

            <entry>Comma-separated names of the optional files
            containing SQL DML statements executed during the
            <classname>SessionFactory creation. This is useful for
            testing or demoing: by adding INSERT statements for example you
            can populate your database with a minimal set of data when it is
            deployed.</para>File order matters, the statements of a give
            file are executed before the statements of the following files.
            These statements are only executed if the schema is created ie if
            <literal>hibernate.hbm2ddl.auto is set to
            <literal>create or
            <literal>create-drop. 
            <literal>/humans.sql,/dogs.sql 
          </row>

          <row>
            <entry>hibernate.bytecode.use_reflection_optimizer

            <entry>Enables the use of bytecode manipulation instead of
            runtime reflection. This is a System-level property and cannot be
            set in <literal>hibernate.cfg.xml. Reflection can
            sometimes be useful when troubleshooting. Hibernate always
            requires either CGLIB or javassist even if you turn off the
            optimizer.</para> e.g.
            <literal>true | false 
          </row>

          <row>
            <entry>hibernate.bytecode.provider

            <entry>Both javassist or cglib can be used as byte
            manipulation engines; the default is
            <literal>javassist.  javassist |
            <literal>cglib 
          </row>
        </tbody>
      </tgroup>
    </table>

    <section id="configuration-optional-dialects" revision="1">
      <title>SQL Dialects

      <para>Always set the hibernate.dialect property to
      the correct <literal>org.hibernate.dialect.Dialect subclass
      for your database. If you specify a dialect, Hibernate will use sensible
      defaults for some of the other properties listed above. This means that
      you will not have to specify them manually.</para>

      <table frame="topbot" id="sql-dialects" revision="3">
        <title>Hibernate SQL Dialects
        (<literal>hibernate.dialect)

        <tgroup cols="2">
          <!--
                    <colspec colwidth="1*"/>
                    <colspec colwidth="2.5*"/>
-->

          <thead>
            <row>
              <entry>RDBMS

              <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>PostgreSQL

              <entry>org.hibernate.dialect.PostgreSQLDialect
            </row>

            <row>
              <entry>MySQL5

              <entry>org.hibernate.dialect.MySQL5Dialect
            </row>

            <row>
              <entry>MySQL5 with InnoDB

              <entry>org.hibernate.dialect.MySQL5InnoDBDialect
            </row>

            <row>
              <entry>MySQL with MyISAM

              <entry>org.hibernate.dialect.MySQLMyISAMDialect
            </row>

            <row>
              <entry>Oracle (any version)

              <entry>org.hibernate.dialect.OracleDialect
            </row>

            <row>
              <entry>Oracle 9i

              <entry>org.hibernate.dialect.Oracle9iDialect
            </row>

            <row>
              <entry>Oracle 10g

              <entry>org.hibernate.dialect.Oracle10gDialect
            </row>

            <row>
              <entry>Oracle 11g

              <entry>org.hibernate.dialect.Oracle10gDialect
            </row>

            <row>
              <entry>Sybase

              <entry>org.hibernate.dialect.SybaseASE15Dialect
            </row>

            <row>
              <entry>Sybase Anywhere

              <entry>org.hibernate.dialect.SybaseAnywhereDialect
            </row>

            <row>
              <entry>Microsoft SQL Server 2000

              <entry>org.hibernate.dialect.SQLServerDialect
            </row>

            <row>
              <entry>Microsoft SQL Server 2005

              <entry>org.hibernate.dialect.SQLServer2005Dialect
            </row>

            <row>
              <entry>Microsoft SQL Server 2008

              <entry>org.hibernate.dialect.SQLServer2008Dialect
            </row>

            <row>
              <entry>SAP DB

              <entry>org.hibernate.dialect.SAPDBDialect
            </row>

            <row>
              <entry>Informix

              <entry>org.hibernate.dialect.InformixDialect
            </row>

            <row>
              <entry>HypersonicSQL

              <entry>org.hibernate.dialect.HSQLDialect
            </row>

            <row>
              <entry>H2 Database

              <entry>org.hibernate.dialect.H2Dialect
            </row>

            <row>
              <entry>Ingres

              <entry>org.hibernate.dialect.IngresDialect
            </row>

            <row>
              <entry>Progress

              <entry>org.hibernate.dialect.ProgressDialect
            </row>

            <row>
              <entry>Mckoi SQL

              <entry>org.hibernate.dialect.MckoiDialect
            </row>

            <row>
              <entry>Interbase

              <entry>org.hibernate.dialect.InterbaseDialect
            </row>

            <row>
              <entry>Pointbase

              <entry>org.hibernate.dialect.PointbaseDialect
            </row>

            <row>
              <entry>FrontBase

              <entry>org.hibernate.dialect.FrontbaseDialect
            </row>

            <row>
              <entry>Firebird

              <entry>org.hibernate.dialect.FirebirdDialect
            </row>
          </tbody>
        </tgroup>
      </table>
    </section>

    <section id="configuration-optional-outerjoin" revision="4">
      <title>Outer Join Fetching

      <para>If your database supports ANSI, Oracle or Sybase style outer
      joins, <emphasis>outer join fetching will often increase
      performance by limiting the number of round trips to and from the
      database. This is, however, at the cost of possibly more work performed
      by the database itself. Outer join fetching allows a whole graph of
      objects connected by many-to-one, one-to-many, many-to-many and
      one-to-one associations to be retrieved in a single SQL
      <literal>SELECT.

      <para>Outer join fetching can be disabled globally
      by setting the property <literal>hibernate.max_fetch_depth to
      <literal>0. A setting of 1 or higher
      enables outer join fetching for one-to-one and many-to-one associations
      that have been mapped with <literal>fetch="join".

      <para>See  for more
      information.</para>
    </section>

    <section id="configuration-optional-binarystreams" revision="1">
      <title>Binary Streams

      <para>Oracle limits the size of byte arrays that can
      be passed to and/or from its JDBC driver. If you wish to use large
      instances of <literal>binary or
      <literal>serializable type, you should enable
      <literal>hibernate.jdbc.use_streams_for_binary. This
      is a system-level setting only.</emphasis>
    </section>

    <section id="configuration-optional-cacheprovider" revision="2">
      <title>Second-level and query cache

      <para>The properties prefixed by hibernate.cache
      allow you to use a process or cluster scoped second-level cache system
      with Hibernate. See the <xref linkend="performance-cache" /> for more
      information.</para>
    </section>

    <section id="configuration-optional-querysubstitution">
      <title>Query Language Substitution

      <para>You can define new Hibernate query tokens using
      <literal>hibernate.query.substitutions. For example:

      <programlisting>hibernate.query.substitutions true=1, false=0

      <para>This would cause the tokens true and
      <literal>false to be translated to integer literals in the
      generated SQL.</para>

      <programlisting>hibernate.query.substitutions toLowercase=LOWER

      <para>This would allow you to rename the SQL LOWER
      function.</para>
    </section>

    <section id="configuration-optional-statistics" revision="2">
      <title>Hibernate statistics

      <para>If you enable hibernate.generate_statistics,
      Hibernate exposes a number of metrics that are useful when tuning a
      running system via <literal>SessionFactory.getStatistics().
      Hibernate can even be configured to expose these statistics via JMX.
      Read the Javadoc of the interfaces in
      <literal>org.hibernate.stats for more information.
    </section>
  </section>

  <section id="configuration-logging">
    <title>Logging

    <para>Hibernate utilizes Simple Logging
    Facade for Java</ulink> (SLF4J) in order to log various system events.
    SLF4J can direct your logging output to several logging frameworks (NOP,
    Simple, log4j version 1.2, JDK 1.4 logging, JCL or logback) depending on
    your chosen binding. In order to setup logging you will need
    <filename>slf4j-api.jar in your classpath together with the jar
    file for your preferred binding - <filename>slf4j-log4j12.jar
    in the case of Log4J. See the SLF4J <ulink
    url="http://www.slf4j.org/manual.html">documentation</ulink> for more
    detail. To use Log4j you will also need to place a
    <filename>log4j.properties file in your classpath. An example
    properties file is distributed with Hibernate in the
    <literal>src/ directory.

    <para>It is recommended that you familiarize yourself with Hibernate's log
    messages. A lot of work has been put into making the Hibernate log as
    detailed as possible, without making it unreadable. It is an essential
    troubleshooting device. The most interesting log categories are the
    following:</para>

    <table frame="topbot" id="log-categories" revision="2">
      <title>Hibernate Log Categories

      <tgroup cols="2">
        <colspec colwidth="1*" />

        <colspec colwidth="2.5*" />

        <thead>
          <row>
            <entry>Category

            <entry>Function
          </row>
        </thead>

        <tbody>
          <row>
            <entry>org.hibernate.SQL

            <entry>Log all SQL DML statements as they are executed
          </row>

          <row>
            <entry>org.hibernate.type

            <entry>Log all JDBC parameters
          </row>

          <row>
            <entry>org.hibernate.tool.hbm2ddl

            <entry>Log all SQL DDL statements as they are executed
          </row>

          <row>
            <entry>org.hibernate.pretty

            <entry>Log the state of all entities (max 20 entities) associated
            with the session at flush time</entry>
          </row>

          <row>
            <entry>org.hibernate.cache

            <entry>Log all second-level cache activity
          </row>

          <row>
            <entry>org.hibernate.transaction

            <entry>Log transaction related activity
          </row>

          <row>
            <entry>org.hibernate.jdbc

            <entry>Log all JDBC resource acquisition
          </row>

          <row>
            <entry>org.hibernate.hql.internal.ast.AST

            <entry>Log HQL and SQL ASTs during query parsing
          </row>

          <row>
            <entry>org.hibernate.secure

            <entry>Log all JAAS authorization requests
          </row>

          <row>
            <entry>org.hibernate

            <entry>Log everything. This is a lot of information but it is
            useful for troubleshooting</entry>
          </row>
        </tbody>
      </tgroup>
    </table>

    <para>When developing applications with Hibernate, you should almost
    always work with <literal>debug enabled for the category
    <literal>org.hibernate.SQL, or, alternatively, the property
    <literal>hibernate.show_sql enabled.
  </section>

  <section id="configuration-namingstrategy">
    <title>Implementing a NamingStrategy

    <para>The interface org.hibernate.cfg.NamingStrategy
    allows you to specify a "naming standard" for database objects and schema
    elements.</para>

    <para>You can provide rules for automatically generating database
    identifiers from Java identifiers or for processing "logical" column and
    table names given in the mapping file into "physical" table and column
    names. This feature helps reduce the verbosity of the mapping document,
    eliminating repetitive noise (<literal>TBL_ prefixes, for
    example). The default strategy used by Hibernate is quite minimal.</para>

    <para>You can specify a different strategy by calling
    <literal>Configuration.setNamingStrategy() before adding
    mappings:</para>

    <programlisting role="JAVA">SessionFactory sf = new Configuration()
    .setNamingStrategy(ImprovedNamingStrategy.INSTANCE)
    .addFile("Item.hbm.xml")
    .addFile("Bid.hbm.xml")
    .buildSessionFactory();</programlisting>

    <para>org.hibernate.cfg.ImprovedNamingStrategy is a
    built-in strategy that might be a useful starting point for some
    applications.</para>
  </section>

  <section>
    <title>Implementing a PersisterClassProvider

    <para>You can configure the persister implementation used to persist your
    entities and collections:</para>

    <itemizedlist>
      <listitem>
        <para>by default, Hibernate uses persisters that make sense in a
        relational model and follow Java Persistence's specification</para>
      </listitem>

      <listitem>
        <para>you can define a PersisterClassProvider
        implementation that provides the persister class used of a given
        entity or collection</para>
      </listitem>

      <listitem>
        <para>finally, you can override them on a per entity and collection
        basis in the mapping using <classname>@Persister or its
        XML equivalent</para>
      </listitem>
    </itemizedlist>

    <para>The latter in the list the higher in priority.

    <para>You can pass the PersisterClassProvider
    instance to the <classname>Configuration object.

    <programlisting role="JAVA">SessionFactory sf = new Configuration()
    .setPersisterClassProvider(customPersisterClassProvider)
    .addAnnotatedClass(Order.class)
    .buildSessionFactory();</programlisting>

    <para>The persister class provider methods, when returning a non null
    persister class, override the default Hibernate persisters. The entity
    name or the collection role are passed to the methods. It is a nice way to
    centralize the overriding logic of the persisters instead of spreading
    them on each entity or collection mapping. </para>
  </section>

  <section id="configuration-xmlconfig" revision="2">
    <title>XML configuration file

    <para>An alternative approach to configuration is to specify a full
    configuration in a file named <literal>hibernate.cfg.xml. This
    file can be used as a replacement for the
    <literal>hibernate.properties file or, if both are present, to
    override properties.</para>

    <para>The XML configuration file is by default expected to be in the root
    of your <literal>CLASSPATH. Here is an example:

    <programlisting role="XML"><?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <!-- a SessionFactory instance listed as /jndi/name -->
    <session-factory
        name="java:hibernate/SessionFactory">

        <!-- properties -->
        <property name="connection.datasource">java:/comp/env/jdbc/MyDB</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">false</property>
        <property name="transaction.factory_class">
            org.hibernate.transaction.JTATransactionFactory
        </property>
        <property name="jta.UserTransaction">java:comp/UserTransaction</property>

        <!-- mapping files -->
        <mapping resource="org/hibernate/auction/Item.hbm.xml"/>
        <mapping resource="org/hibernate/auction/Bid.hbm.xml"/>

        <!-- cache settings -->
        <class-cache class="org.hibernate.auction.Item" usage="read-write"/>
        <class-cache class="org.hibernate.auction.Bid" usage="read-only"/>
        <collection-cache collection="org.hibernate.auction.Item.bids" usage="read-write"/>

    </session-factory>

</hibernate-configuration></programlisting>

    <para>The advantage of this approach is the externalization of the mapping
    file names to configuration. The <literal>hibernate.cfg.xml is
    also more convenient once you have to tune the Hibernate cache. It is your
    choice to use either <literal>hibernate.properties or
    <literal>hibernate.cfg.xml. Both are equivalent, except for the
    above mentioned benefits of using the XML syntax.</para>

    <para>With the XML configuration, starting Hibernate is then as simple
    as:</para>

    <programlisting role="JAVA">SessionFactory sf = new Configuration().configure().buildSessionFactory();

    <para>You can select a different XML configuration file using:

    <programlisting role="JAVA">SessionFactory sf = new Configuration()
    .configure("catdb.cfg.xml")
    .buildSessionFactory();</programlisting>
  </section>

  <section id="configuration-j2ee" revision="1">
    <title>Java EE Application Server integration

    <para>Hibernate has the following integration points for J2EE
    infrastructure:</para>

    <itemizedlist>
      <listitem>
        <para>Container-managed datasources: Hibernate
        can use JDBC connections managed by the container and provided through
        JNDI. Usually, a JTA compatible <literal>TransactionManager
        and a <literal>ResourceManager take care of transaction
        management (CMT), especially distributed transaction handling across
        several datasources. You can also demarcate transaction boundaries
        programmatically (BMT), or you might want to use the optional
        Hibernate <literal>Transaction API for this to keep your
        code portable.</para>
      </listitem>
    </itemizedlist>

    <itemizedlist>
      <listitem>
        <para>Automatic JNDI binding: Hibernate can bind
        its <literal>SessionFactory to JNDI after startup.
      </listitem>
    </itemizedlist>

    <itemizedlist>
      <listitem>
        <para>JTA Session binding: the Hibernate
        <literal>Session can be automatically bound to the scope of
        JTA transactions. Simply lookup the <literal>SessionFactory
        from JNDI and get the current <literal>Session. Let
        Hibernate manage flushing and closing the <literal>Session
        when your JTA transaction completes. Transaction demarcation is either
        declarative (CMT) or programmatic (BMT/UserTransaction).</para>
      </listitem>
    </itemizedlist>

    <itemizedlist>
      <listitem>
        <para>JMX deployment: if you have a JMX capable
        application server (e.g. JBoss AS), you can choose to deploy Hibernate
        as a managed MBean. This saves you the one line startup code to build
        your <literal>SessionFactory from a
        <literal>Configuration. The container will startup your
        <literal>HibernateService and also take care of service
        dependencies (datasource has to be available before Hibernate starts,
        etc).</para>
      </listitem>
    </itemizedlist>

    <para>Depending on your environment, you might have to set the
    configuration option
    <literal>hibernate.connection.aggressive_release to true if your
    application server shows "connection containment" exceptions.</para>

    <section id="configuration-optional-transactionstrategy" revision="3">
      <title>Transaction strategy configuration

      <para>The Hibernate Session API is independent of any
      transaction demarcation system in your architecture. If you let
      Hibernate use JDBC directly through a connection pool, you can begin and
      end your transactions by calling the JDBC API. If you run in a J2EE
      application server, you might want to use bean-managed transactions and
      call the JTA API and <literal>UserTransaction when
      needed.</para>

      <para>To keep your code portable between these two (and other)
      environments we recommend the optional Hibernate
      <literal>Transaction API, which wraps and hides the underlying
      system. You have to specify a factory class for
      <literal>Transaction instances by setting the Hibernate
      configuration property
      <literal>hibernate.transaction.factory_class.

      <para>There are three standard, or built-in, choices:

      <variablelist spacing="compact">
        <varlistentry>
          <term>org.hibernate.transaction.JDBCTransactionFactory

          <listitem>
            <para>delegates to database (JDBC) transactions (default)
          </listitem>
        </varlistentry>

        <varlistentry>
          <term>org.hibernate.transaction.JTATransactionFactory

          <listitem>
            <para>delegates to container-managed transactions if an existing
            transaction is underway in this context (for example, EJB session
            bean method). Otherwise, a new transaction is started and
            bean-managed transactions are used.</para>
          </listitem>
        </varlistentry>

        <varlistentry>
          <term>org.hibernate.transaction.CMTTransactionFactory

          <listitem>
            <para>delegates to container-managed JTA transactions
          </listitem>
        </varlistentry>
      </variablelist>

      <para>You can also define your own transaction strategies (for a CORBA
      transaction service, for example).</para>

      <para>Some features in Hibernate (i.e., the second level cache,
      Contextual Sessions with JTA, etc.) require access to the JTA
      <literal>TransactionManager in a managed environment. In an
      application server, since J2EE does not standardize a single mechanism,
      you have to specify how Hibernate should obtain a reference to the
      <literal>TransactionManager:

      <table frame="topbot" id="jtamanagerlookup" revision="1">
        <title>JTA TransactionManagers

        <tgroup cols="2">
          <colspec colwidth="2.5*" />

          <colspec colwidth="1*" />

          <thead>
            <row>
              <entry>Transaction Factory

              <entry align="center">Application Server
            </row>
          </thead>

          <tbody>
            <row>
              <entry>org.hibernate.transaction.JBossTransactionManagerLookup

              <entry align="center">JBoss AS
            </row>

            <row>
              <entry>org.hibernate.transaction.WeblogicTransactionManagerLookup

              <entry align="center">Weblogic
            </row>

            <row>
              <entry>org.hibernate.transaction.WebSphereTransactionManagerLookup

              <entry align="center">WebSphere
            </row>

            <row>
              <entry>org.hibernate.transaction.WebSphereExtendedJTATransactionLookup

              <entry align="center">WebSphere 6
            </row>

            <row>
              <entry>org.hibernate.transaction.OrionTransactionManagerLookup

              <entry align="center">Orion
            </row>

            <row>
              <entry>org.hibernate.transaction.ResinTransactionManagerLookup

              <entry align="center">Resin
            </row>

            <row>
              <entry>org.hibernate.transaction.JOTMTransactionManagerLookup

              <entry align="center">JOTM
            </row>

            <row>
              <entry>org.hibernate.transaction.JOnASTransactionManagerLookup

              <entry align="center">JOnAS
            </row>

            <row>
              <entry>org.hibernate.transaction.JRun4TransactionManagerLookup

              <entry align="center">JRun4
            </row>

            <row>
              <entry>org.hibernate.transaction.BESTransactionManagerLookup

              <entry align="center">Borland ES
            </row>

            <row>
              <entry>org.hibernate.transaction.JBossTSStandaloneTransactionManagerLookup

              <entry align="center">JBoss TS used standalone (ie. outside
              JBoss AS and a JNDI environment generally). Known to work for
              <literal>org.jboss.jbossts:jbossjta:4.11.0.Final
            </row>
          </tbody>
        </tgroup>
      </table>
    </section>

    <section id="configuration-optional-jndi" revision="3">
      <title>JNDI-bound SessionFactory

      <para>A JNDI-bound Hibernate SessionFactory can
      simplify the lookup function of the factory and create new
      <literal>Sessions. This is not, however, related to a JNDI
      bound <literal>Datasource; both simply use the same
      registry.</para>

      <para>If you wish to have the SessionFactory bound to
      a JNDI namespace, specify a name (e.g.
      <literal>java:hibernate/SessionFactory) using the property
      <literal>hibernate.session_factory_name. If this property is
      omitted, the <literal>SessionFactory will not be bound to
      JNDI. This is especially useful in environments with a read-only JNDI
      default implementation (in Tomcat, for example).</para>

      <para>When binding the SessionFactory to JNDI,
      Hibernate will use the values of <literal>hibernate.jndi.url,
      <literal>hibernate.jndi.class to instantiate an initial
      context. If they are not specified, the default
      <literal>InitialContext will be used.

      <para>Hibernate will automatically place the
      <literal>SessionFactory in JNDI after you call
      <literal>cfg.buildSessionFactory(). This means you will have
      this call in some startup code, or utility class in your application,
      unless you use JMX deployment with the
      <literal>HibernateService (this is discussed later in greater
      detail).</para>

      <para>If you use a JNDI SessionFactory, an EJB or any
      other class, you can obtain the <literal>SessionFactory using
      a JNDI lookup.</para>

      <para>It is recommended that you bind the
      <literal>SessionFactory to JNDI in a managed environment and
      use a <literal>static singleton otherwise. To shield your
      application code from these details, we also recommend to hide the
      actual lookup code for a <literal>SessionFactory in a helper
      class, such as <literal>HibernateUtil.getSessionFactory().
      Note that such a class is also a convenient way to startup Hibernate—see
      chapter 1.</para>
    </section>

    <section id="configuration-j2ee-currentsession" revision="4">
      <title>Current Session context management with JTA

      <para>The easiest way to handle Sessions and
      transactions is Hibernate's automatic "current"
      <literal>Session management. For a discussion of contextual
      sessions see <xref linkend="architecture-current-session" />. Using the
      <literal>"jta" session context, if there is no Hibernate
      <literal>Session associated with the current JTA transaction,
      one will be started and associated with that JTA transaction the first
      time you call <literal>sessionFactory.getCurrentSession(). The
      <literal>Sessions retrieved via
      <literal>getCurrentSession() in the "jta"
      context are set to automatically flush before the transaction completes,
      close after the transaction completes, and aggressively release JDBC
      connections after each statement. This allows the
      <literal>Sessions to be managed by the life cycle of the JTA
      transaction to which it is associated, keeping user code clean of such
      management concerns. Your code can either use JTA programmatically
      through <literal>UserTransaction, or (recommended for portable
      code) use the Hibernate <literal>Transaction API to set
      transaction boundaries. If you run in an EJB container, declarative
      transaction demarcation with CMT is preferred.</para>
    </section>

    <section id="configuration-j2ee-jmx" revision="1">
      <title>JMX deployment

      <para>The line cfg.buildSessionFactory() still has to
      be executed somewhere to get a <literal>SessionFactory into
      JNDI. You can do this either in a <literal>static initializer
      block, like the one in <literal>HibernateUtil, or you can
      deploy Hibernate as a <emphasis>managed service.

      <para>Hibernate is distributed with
      <literal>org.hibernate.jmx.HibernateService for deployment on
      an application server with JMX capabilities, such as JBoss AS. The
      actual deployment and configuration is vendor-specific. Here is an
      example <literal>jboss-service.xml for JBoss 4.0.x:

      <programlisting role="XML"><?xml version="1.0"?>
<server>

<mbean code="org.hibernate.jmx.HibernateService"
    name="jboss.jca:service=HibernateFactory,name=HibernateFactory">

    <!-- Required services -->
    <depends>jboss.jca:service=RARDeployer</depends>
    <depends>jboss.jca:service=LocalTxCM,name=HsqlDS</depends>

    <!-- Bind the Hibernate service to JNDI -->
    <attribute name="JndiName">java:/hibernate/SessionFactory</attribute>

    <!-- Datasource settings -->
    <attribute name="Datasource">java:HsqlDS</attribute>
    <attribute name="Dialect">org.hibernate.dialect.HSQLDialect</attribute>

    <!-- Transaction integration -->
    <attribute name="TransactionStrategy">
        org.hibernate.transaction.JTATransactionFactory</attribute>
    <attribute name="TransactionManagerLookupStrategy">
        org.hibernate.transaction.JBossTransactionManagerLookup</attribute>
    <attribute name="FlushBeforeCompletionEnabled">true</attribute>
    <attribute name="AutoCloseSessionEnabled">true</attribute>

    <!-- Fetching options -->
    <attribute name="MaximumFetchDepth">5</attribute>

    <!-- Second-level caching -->
    <attribute name="SecondLevelCacheEnabled">true</attribute>
    <attribute name="CacheProviderClass">org.hibernate.cache.internal.EhCacheProvider</attribute>
    <attribute name="QueryCacheEnabled">true</attribute>

    <!-- Logging -->
    <attribute name="ShowSqlEnabled">true</attribute>

    <!-- Mapping files -->
    <attribute name="MapResources">auction/Item.hbm.xml,auction/Category.hbm.xml</attribute>

</mbean>

</server></programlisting>

      <para>This file is deployed in a directory called
      <literal>META-INF and packaged in a JAR file with the
      extension <literal>.sar (service archive). You also need to
      package Hibernate, its required third-party libraries, your compiled
      persistent classes, as well as your mapping files in the same archive.
      Your enterprise beans (usually session beans) can be kept in their own
      JAR file, but you can include this EJB JAR file in the main service
      archive to get a single (hot-)deployable unit. Consult the JBoss AS
      documentation for more information about JMX service and EJB
      deployment.</para>
    </section>
  </section>
</chapter>

Other Hibernate examples (source code examples)

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

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

#1 New Release!

FP Best Seller

 

new blog posts

 

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

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