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

bean, entitymanager, hibernate, hibernate, java, java, jpa, the, this, this, validation, xml, xml, you

The Hibernate configuration.xml source code

<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ Copyright (c) 2008, Red Hat Inc 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 Inc.
  ~
  ~ 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">
<chapter id="configuration">
  <title id="setup">Setup and configuration

  <section>
    <title>Setup

    <para>The JPA 2.0 compatible Hibernate EntityManager is built on top of
    the core of Hibernate and Hibernate Annotations. Starting from version
    3.5, we have bundled in a single Hibernate distribution all the necessary
    modules:</para>

    <itemizedlist>
      <listitem>
        <para>Hibernate Core: the native Hibernate APIs and core engine
      </listitem>

      <listitem>
        <para>Hibernate Annotations: the annotation-based mapping
      </listitem>

      <listitem>
        <para>Hibernate EntityManager: the JPA 2.0 APIs and livecycle semantic
        implementation</para>
      </listitem>
    </itemizedlist>

    <para>Download the Hibernate Core distribution. Set up your classpath
    (after you have created a new project in your favorite IDE):<itemizedlist>
        <listitem>
          <para>Copy hibernate3.jar and the required 3rd
          party libraries available in
          <filename>lib/required.
        </listitem>

        <listitem>
          <para>Copy
          <filename>lib/jpa/hibernate-jpa-2.0-api-1.0.0.Final.jar
          to your classpath as well.</para>
        </listitem>
      </itemizedlist>

    <note>
      <title>What is hibernate-jpa-2.0-api-x.y.z.jar?

      <para>This is the JAR containing the JPA 2.0 API, it provides all the
      interfaces and concrete classes that the specification defines as public
      API. Said otherwise, you can use this JAR to bootstrap any JPA provider
      implementation. Note that you typically don't need it when you deploy
      your application in a Java EE 6 application server (like JBoss AS 6 for
      example).</para>
    </note>

    <para>Alternatively, if you use Maven, add the following
    dependencies</para>

    <programlisting language="XML" role="XML"><project ...>
  ...
  <dependencies>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>${hibernate-core-version}</version>
    </dependency>
  </dependencies>
</project></programlisting>

    <para>All the required dependencies like hibernate-core and
    hibernate-annotations will be dragged transitively.</para>

    <para>We recommend you use  and the
    Bean Validation specification capabilities as its integration with Java
    Persistence 2 has been standardized. Download Hibernate Validator 4 or
    above from the Hibernate website and add
    <filename>hibernate-validator.jar and
    <filename>validation-api.jar in your classpath. Alternatively
    add the following dependency in your <filename>pom.xml.

    <programlisting language="XML" role="XML"><project>
  ...
  <dependencies>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>${hibernate-validator-version}</version>
    </dependency>
    ...
  </dependencies>
  ...
</project></programlisting>

    <para>If you wish to use  (full-text
    search for Hibernate aplications), download it from the Hibernate website
    and add <filename>hibernate-search.jar and its dependencies in
    your classpath. Alternatively add the following dependency in your
    <filename>pom.xml.

    <programlisting language="XML" role="XML"><project>
  ...
  <dependencies>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-search</artifactId>
      <version>${hibernate-search-version}</version>
    </dependency>
    ...
  </dependencies>
  ...
</project></programlisting>
  </section>

  <section id="setup-configuration"
           xreflabel="Configuration and bootstrapping">
    <title>Configuration and bootstrapping

    <section id="setup-configuration-packaging" revision="1">
      <title>Packaging

      <para>The configuration for entity managers both inside an application
      server and in a standalone application reside in a persistence archive.
      A persistence archive is a JAR file which must define a
      <literal>persistence.xml file that resides in the
      <filename>META-INF folder. All properly annotated classes
      included in the archive (ie. having an <literal>@Entity
      annotation), all annotated packages and all Hibernate hbm.xml files
      included in the archive will be added to the persistence unit
      configuration, so by default, your persistence.xml will be quite
      minimalist:</para>

      <programlisting language="XML" role="XML"><persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">
   <persistence-unit name="sample">
      <jta-data-source>java:/DefaultDS</jta-data-source>
      <properties>
         <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
         <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
      </properties>
   </persistence-unit>
</persistence></programlisting>

      <para>Here's a more complete example of a
      <filename>persistence.xml file

      <programlisting language="XML" role="XML"><persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">
   <persistence-unit name="manager1" transaction-type="JTA">
      <provider>org.hibernate.ejb.HibernatePersistence</provider>
      <jta-data-source>java:/DefaultDS</jta-data-source>
      <mapping-file>ormap.xml</mapping-file>
      <jar-file>MyApp.jar</jar-file>
      <class>org.acme.Employee</class>
      <class>org.acme.Person</class>
      <class>org.acme.Address</class>
      <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
      <validation-mode>CALLBACK</validation-mode>
      <properties>
         <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
         <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
      </properties>
   </persistence-unit>
</persistence></programlisting>

      <variablelist spacing="compact">
        <varlistentry>
          <term>name

          <listitem>
            <para>(attribute) Every entity manager must have a name.
          </listitem>
        </varlistentry>

        <varlistentry>
          <term>transaction-type

          <listitem>
            <para>(attribute) Transaction type used. Either JTA or
            RESOURCE_LOCAL (default to JTA in a JavaEE environment and to
            RESOURCE_LOCAL in a JavaSE environment). When a jta-datasource is
            used, the default is JTA, if non-jta-datasource is used,
            RESOURCE_LOCAL is used.</para>
          </listitem>
        </varlistentry>

        <varlistentry>
          <term>provider

          <listitem>
            <para>The provider is a fully-qualified class name of the EJB
            Persistence provider. You do not have to define it if you don't
            work with several EJB3 implementations. This is needed when you
            are using multiple vendor implementations of EJB
            Persistence.</para>
          </listitem>
        </varlistentry>

        <varlistentry>
          <term>jta-data-source,
          <code>non-jta-data-source

          <listitem>
            <para>This is the JNDI name of where the javax.sql.DataSource is
            located. When running without a JNDI available Datasource, you
            must specify JDBC connections with Hibernate specific properties
            (see below).</para>
          </listitem>
        </varlistentry>

        <varlistentry>
          <term>mapping-file

          <listitem>
            <para>The class element specifies a EJB3 compliant XML mapping
            file that you will map. The file has to be in the classpath. As
            per the EJB3 specification, Hibernate EntityManager will try to
            load the mapping file located in the jar file at
            <literal>META_INF/orm.xml. Of course any explicit
            mapping file will be loaded too. As a matter of fact, you can
            provide any XML file in the mapping file element ie. either hbm
            files or EJB3 deployment descriptor.</para>
          </listitem>
        </varlistentry>

        <varlistentry>
          <term>jar-file

          <listitem>
            <para>The jar-file elements specifies a jar to analyse. All
            properly annotated classes, annotated packages and all hbm.xml
            files part of this jar file will be added to the persistence unit
            configuration. This element is mainly used in Java EE environment.
            Use of this one in Java SE should be considered as non portable,
            in this case a absolute url is needed. You can alternatively point
            to a directory (This is especially useful when in your test
            environment, the persistence.xml file is not under the same root
            directory or jar than your domain model).</para>

            <programlisting language="XML" role="XML">        <jar-file>file:/home/turin/work/local/lab8/build/classes</jar-file>
          </listitem>
        </varlistentry>

        <varlistentry>
          <term>exclude-unlisted-classes

          <listitem>
            <para>Do not check the main jar file for annotated classes. Only
            explicit classes will be part of the persistence unit.</para>
          </listitem>
        </varlistentry>

        <varlistentry>
          <term>class

          <listitem>
            <para>The class element specifies a fully qualified class name
            that you will map. By default all properly annotated classes and
            all hbm.xml files found inside the archive are added to the
            persistence unit configuration. You can add some external entity
            through the class element though. As an extension to the
            specification, you can add a package name in the
            <literal><class> element (eg
            <code><class>org.hibernate.eg</class>).
            Caution, the package will include the metadata defined at the
            package level (ie in <filename>package-info.java), it
            will not include all the classes of a given package.</para>
          </listitem>
        </varlistentry>

        <varlistentry>
          <term>shared-cache-mode

          <listitem>
            <para>By default, entities are elected for second-level cache if
            annotated with <classname>@Cacheable. You can
            however:</para>

            <itemizedlist>
              <listitem>
                <para>ALL: force caching for all
                entities</para>
              </listitem>

              <listitem>
                <para>NONE: disable caching for all
                entities (useful to take second-level cache out of the
                equation)</para>
              </listitem>

              <listitem>
                <para>ENABLE_SELECTIVE (default): enable
                caching when explicitly marked</para>
              </listitem>

              <listitem>
                <para>DISABLE_SELECTIVE: enable caching
                unless explicitly marked as
                <classname>@Cacheable(false) (not
                recommended)</para>
              </listitem>
            </itemizedlist>

            <para>See Hibernate Annotation's documentation for more
            details.</para>
          </listitem>
        </varlistentry>

        <varlistentry>
          <term>validation-mode

          <listitem>
            <para>By default, Bean Validation (and Hibernate Validator) is
            activated. When an entity is created, updated (and optionally
            deleted), it is validated before being sent to the database. The
            database schema generated by Hibernate also reflects the
            constraints declared on the entity.</para>

            <para>You can fine-tune that if needed:

            <itemizedlist>
              <listitem>
                <para>AUTO: if Bean Validation is present
                in the classpath, CALLBACK and DDL are activated.</para>
              </listitem>

              <listitem>
                <para>CALLBACK: entities are validated on
                creation, update and deletion. If no Bean Validation provider
                is present, an exception is raised at initialization
                time.</para>
              </listitem>

              <listitem>
                <para>DDL: (not standard, see below)
                database schemas are entities are validated on creation,
                update and deletion. If no Bean Validation provider is
                present, an exception is raised at initialization time.</para>
              </listitem>

              <listitem>
                <para>NONE: Bean Validation is not used at
                all</para>
              </listitem>
            </itemizedlist>

            <para>Unfortunately, DDL is not standard mode
            (though extremely useful) and you will not be able to put it in
            <literal><validation-mode>. To use it, add a
            regular property</para>

            <programlisting language="XML" role="XML"><property name="javax.persistence.validation.mode">
  ddl
</property></programlisting>

            <para>With this approach, you can mix ddl and callback
            modes:</para>

            <programlisting language="XML" role="XML"><property name="javax.persistence.validation.mode">
  ddl, callback
</property></programlisting>
          </listitem>
        </varlistentry>

        <varlistentry>
          <term>properties

          <listitem>
            <para>The properties element is used to specify vendor specific
            properties. This is where you will define your Hibernate specific
            configurations. This is also where you will have to specify JDBC
            connection information as well.</para>

            <para>Here is a list of JPA 2 standard properties. Be sure to also
            Hibernate Core's documentation to see Hibernate specific
            properties.</para>

            <itemizedlist>
              <listitem>
                <para>javax.persistence.lock.timeout
                pessimistic lock timeout in milliseconds
                (<classname>Integer or
                <classname>String), this is a hint used by
                Hibernate but requires support by your underlying
                database.</para>
              </listitem>

              <listitem>
                <para>javax.persistence.query.timeout query
                timeout in milliseconds (<classname>Integer or
                <classname>String), this is a hint used by
                Hibernate but requires support by your underlying database
                (TODO is that 100% true or do we use some other
                tricks).</para>
              </listitem>

              <listitem>
                <para>javax.persistence.validation.mode
                corresponds to the <literal>validation-mode element.
                Use it if you wish to use the non standard
                <literal>DDL value.
              </listitem>

              <listitem>
                <para>javax.persistence.validation.group.pre-persist
                defines the group or list of groups to validate before
                persisting an entity. This is a comma separated fully
                qualified class name string (eg
                <code>com.acme.groups.Common or
                <code>com.acme.groups.Common,
                javax.validation.groups.Default</code>). Defaults to the Bean
                Validation default group.</para>
              </listitem>

              <listitem>
                <para>javax.persistence.validation.group.pre-update
                defines the group or list of groups to validate before
                updating an entity. This is a comma separated fully qualified
                class name string (eg <code>com.acme.groups.Common or
                <code>com.acme.groups.Common,
                javax.validation.groups.Default</code>). Defaults to the Bean
                Validation default group.</para>
              </listitem>

              <listitem>
                <para>javax.persistence.validation.group.pre-remove
                defines the group or list of groups to validate before
                persisting an entity. This is a comma separated fully
                qualified class name string (eg
                <code>com.acme.groups.Common or
                <code>com.acme.groups.Common,
                javax.validation.groups.Default</code>). Defaults to no
                group.</para>
              </listitem>
            </itemizedlist>

            <note>
              <para>To know more about Bean Validation and Hibernate
              Validator, check out Hibernate Validator's reference
              documentation as well as Hibernate Annotations's documentation
              on Bean Validation.</para>
            </note>

            <para>The following properties can only be used in a SE
            environment where no datasource/JNDI is available:</para>

            <itemizedlist>
              <listitem>
                <para>javax.persistence.jdbc.driver: the
                fully qualified class name of the driver class</para>
              </listitem>

              <listitem>
                <para>javax.persistence.jdbc.url: the
                driver specific URL</para>
              </listitem>

              <listitem>
                <para>javax.persistence.jdbc.user the user
                name used for the database connection</para>
              </listitem>

              <listitem>
                <para>javax.persistence.jdbc.password the
                password used for the database connection</para>
              </listitem>
            </itemizedlist>
          </listitem>
        </varlistentry>
      </variablelist>

      <para>Be sure to define the grammar definition in the
      <literal>persistence element since the JPA specification
      requires schema validation. If the <literal>systemId ends with
      <literal>persistence_2_0.xsd, Hibernate entityManager will use
      the version embedded in the hibernate-entitymanager.jar. It won't fetch
      the resource from the internet.</para>

      <programlisting language="XML" role="XML"><persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0"></programlisting>
    </section>

    <section id="setup-configuration-bootstrapping" revision="1">
      <title>Bootstrapping

      <para>The JPA specification defines a bootstrap procedure to access the
      <classname>EntityManagerFactory and the
      <classname>EntityManager. The bootstrap class is
      <classname>javax.persistence.Persistence, e.g.

      <programlisting language="JAVA" role="JAVA">EntityManagerFactory emf = Persistence.createEntityManagerFactory("manager1");

//or

Map<String, Object> configOverrides = new HashMap<String, Object>();
configOverrides.put("hibernate.hbm2ddl.auto", "create-drop");
EntityManagerFactory programmaticEmf =
    Persistence.createEntityManagerFactory("manager1", configOverrides);</programlisting>

      <para>The first version is equivalent to the second with an empty map.
      The map version is a set of overrides that will take precedence over any
      properties defined in your <filename>persistence.xml files.
      All the properties defined in <xref
      linkend="setup-configuration-packaging" /> can be passed to the
      <methodname>createEntityManagerFactory method and there are
      a few additional ones:</para>

      <itemizedlist>
        <listitem>
          <para>javax.persistence.provider to define the
          provider class used</para>
        </listitem>

        <listitem>
          <para>javax.persistence.transactionType to define
          the transaction type used (either <literal>JTA or
          <literal>RESOURCE_LOCAL)
        </listitem>

        <listitem>
          <para>javax.persistence.jtaDataSource to define
          the JTA datasource name in JNDI</para>
        </listitem>

        <listitem>
          <para>javax.persistence.nonJtaDataSource to
          define the non JTA datasource name in JNDI</para>
        </listitem>

        <listitem>
          <para>javax.persistence.lock.timeout pessimistic
          lock timeout in milliseconds (<classname>Integer or
          <classname>String)
        </listitem>

        <listitem>
          <para>javax.persistence.query.timeout query
          timeout in milliseconds (<classname>Integer or
          <classname>String)
        </listitem>

        <listitem>
          <para>javax.persistence.sharedCache.mode
          corresponds to the <literal>share-cache-mode element
          defined in <xref linkend="setup-configuration-packaging" />.
        </listitem>

        <listitem>
          <para>javax.persistence.validation.mode
          corresponds to the <literal>validation-mode element
          defined in <xref linkend="setup-configuration-packaging" />.
        </listitem>
      </itemizedlist>

      <para>When Persistence.createEntityManagerFactory() is
      called, the persistence implementation will search your classpath for
      any <code>META-INF/persistence.xml files using the
      <code>ClassLoader.getResource("META-INF/persistence.xml") method.
      Actually the <classname>Persistence class will look at all
      the Persistence Providers available in the classpath and ask each of
      them if they are responsible for the creation of the entity manager
      factory <literal>manager1. Each provider, from this list of
      resources, it will try to find an entity manager that matches the name
      you specify in the command line with what is specified in the
      persistence.xml file (of course the provider <literal>element
      must match the current persistent provider). If no persistence.xml with
      the correct name are found or if the expected persistence provider is
      not found, a <classname>PersistenceException is
      raised.</para>

      <para>Apart from Hibernate system-level settings, all the properties
      available in Hibernate can be set in <code>properties element of
      the persistence.xml file or as an override in the map you pass to
      <code>createEntityManagerFactory(). Please refer to the Hibernate
      reference documentation for a complete listing. There are however a
      couple of properties available in the EJB3 provider only.</para>

      <table>
        <title>Hibernate Entity Manager specific properties

        <tgroup cols="2">
          <colspec align="left" colname="c1" />

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

          <thead>
            <row>
              <entry>Property name

              <entry>Description
            </row>
          </thead>

          <tbody>
            <row>
              <entry>hibernate.ejb.classcache.<classname>

              <entry>class cache strategy [comma cache region] of the class
              Default to no cache, and default region cache to
              fully.qualified.classname (eg.
              hibernate.ejb.classcache.com.acme.Cat read-write or
              hibernate.ejb.classcache.com.acme.Cat read-write,
              MyRegion).</entry>
            </row>

            <row>
              <entry>hibernate.ejb.collectioncache.<collectionrole>

              <entry>collection cache strategy [comma cache region] of the
              class Default to no cache, and default region cache to
              fully.qualified.classname.role (eg.
              hibernate.ejb.classcache.com.acme.Cat read-write or
              hibernate.ejb.classcache.com.acme.Cat read-write,
              MyRegion).</entry>
            </row>

            <row>
              <entry>hibernate.ejb.cfgfile

              <entry>XML configuration file to use to configure Hibernate (eg.
              <filename>/hibernate.cfg.xml).
            </row>

            <row>
              <entry>hibernate.archive.autodetection

              <entry>Determine which element is auto discovered by Hibernate
              Entity Manager while parsing the .par archive. (default to
              <literal>class,hbm).
            </row>

            <row>
              <entry>hibernate.ejb.interceptor

              <entry>An optional Hibernate interceptor. The interceptor
              instance is shared by all <classname>Session
              instances. This interceptor has to implement
              <classname>org.hibernate.Interceptor and have a
              no-arg constructor. This property can not be combined with
              <literal>hibernate.ejb.interceptor.session_scoped.
            </row>

            <row>
              <entry>hibernate.ejb.interceptor.session_scoped

              <entry>An optional Hibernate interceptor. The interceptor
              instance is specific to a given <classname>Session
              instance (and hence can be non thread-safe). This interceptor
              has to implement
              <classname>org.hibernate.Interceptor and have a
              no-arg constructor. This property can not be combined with
              <literal>hibernate.ejb.interceptor.
            </row>

            <row>
              <entry>hibernate.ejb.naming_strategy

              <entry>An optional naming strategy. The class must have a no-arg
              constructor. The default naming strategy used is
              <classname>EJB3NamingStrategy. You also might want
              to consider the
              <classname>DefaultComponentSafeNamingStrategy.
            </row>

            <row>
              <entry>hibernate.ejb.persister_class_provider

              <entry>A optional PersisterClassProvider
              implementation class name. The class must have a no-arg
              constructor.</entry>
            </row>

            <row>
              <entry>hibernate.ejb.session_factory_observer

              <entry>A optional SessionFactoryObserver
              implementation class name. The class must have a no-arg
              constructor.</entry>
            </row>

            <row>
              <entry>hibernate.ejb.event.<eventtype>

              <entry>Event listener list for a given eventtype. The list of
              event listeners is a comma separated fully qualified class name
              list (eg. hibernate.ejb.event.pre-load
              com.acme.SecurityListener, com.acme.AuditListener)</entry>
            </row>

            <row>
              <entry>hibernate.ejb.use_class_enhancer

              <entry>Whether or not use Application server class enhancement
              at deployment time (default to false)</entry>
            </row>

            <row>
              <entry>hibernate.ejb.discard_pc_on_close

              <entry>If true, the persistence context will be discarded (think
              clear() when the method is called. Otherwise the persistence
              context will stay alive till the transaction completion: all
              objects will remain managed, and any change will be synchronized
              with the database (default to false, ie wait the transaction
              completion)</entry>
            </row>

            <row>
              <entry>hibernate.ejb.resource_scanner

              <entry>By default, Hibernate EntityManager scans itself
              the list of resources for annotated classes and persistence
              deployment descriptors (like orm.xml and hbm.xml
              files).</para>You can customize this scanning strategy by
              implementing
              <classname>org.hibernate.ejb.packaging.Scanner. This
              property is used by container implementors to improve
              integration with Hibernate.</para>Accepts an instance of
              <classname>Scanner or the file name of a no-arg
              constructor class implementing
              <classname>Scanner.
            </row>
          </tbody>
        </tgroup>
      </table>

      <para>Note that you can mix XML <class>
      declaration and <literal>hibernate.ejb.cfgfile usage in the
      same configuration. Be aware of the potential clashed. The properties
      set in <filename>persistence.xml will override the one in the
      defined <filename>hibernate.cfg.xml.

      <note>
        <para>It is important that you do not override
        <literal>hibernate.transaction.factory_class, Hibernate
        EntityManager automatically set the appropriate transaction factory
        depending on the EntityManager type (ie <literal>JTA versus
        <literal>RESOURSE_LOCAL). If you are working in a Java EE
        environment, you might want to set the
        <literal>hibernate.transaction.manager_lookup_class
        though.</para>
      </note>

      <para>Here is a typical configuration in a Java SE environment

      <programlisting language="XML" role="XML"><persistence>
   <persistence-unit name="manager1" transaction-type="RESOURCE_LOCAL">
      <class>org.hibernate.ejb.test.Cat</class>
      <class>org.hibernate.ejb.test.Distributor</class>
      <class>org.hibernate.ejb.test.Item</class>
      <properties>
         <property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver"/>
         <property name="javax.persistence.jdbc.user" value="sa"/>
         <property name="javax.persistence.jdbc.password" value=""/>
         <property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:."/>
         <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/
         <property name="hibernate.max_fetch_depth" value="3"/>
       
         <!-- cache configuration -->
         <property name="hibernate.ejb.classcache.org.hibernate.ejb.test.Item" value="read-write"/>
         <property name="hibernate.ejb.collectioncache.org.hibernate.ejb.test.Item.distributors" value="read-write, RegionName"/>

         <!-- alternatively to <class> and <property> declarations, you can use a regular hibernate.cfg.xml file -->
         <!-- property name="hibernate.ejb.cfgfile" value="/org/hibernate/ejb/test/hibernate.cfg.xml"/ -->
      </properties>
   </persistence-unit>
</persistence></programlisting>

      <para>To ease the programmatic configuration, Hibernate Entity Manager
      provide a proprietary API. This API is very similar to the
      <classname>Configuration API and share the same concepts:
      <classname>Ejb3Configuration. Refer to the JavaDoc and the
      Hibernate reference guide for more detailed informations on how to use
      it.</para>

      <para>TODO: me more descriptive on some APIs like setDatasource()

      <programlisting language="JAVA" role="JAVA">Ejb3Configuration cfg = new Ejb3Configuration();
EntityManagerFactory emf = 
  cfg.addProperties( properties ) //add some properties
     .setInterceptor( myInterceptorImpl ) // set an interceptor
     .addAnnotatedClass( MyAnnotatedClass.class ) //add a class to be mapped
     .addClass( NonAnnotatedClass.class ) //add an hbm.xml file using the Hibernate convention
     .addRerousce( "mypath/MyOtherCLass.hbm.xml ) //add an hbm.xml file
     .addRerousce( "mypath/orm.xml ) //add an EJB3 deployment descriptor
     .configure("/mypath/hibernate.cfg.xml") //add a regular hibernate.cfg.xml
     .buildEntityManagerFactory(); //Create the entity manager factory</programlisting>
    </section>
  </section>

  <section>
    <title>Event listeners

    <para>Hibernate Entity Manager needs to enhance Hibernate core to
    implements all the JPA semantics. It does that through the event listener
    system of Hibernate. Be careful when you use the event system yourself,
    you might override some of the JPA semantics. A safe way is to add your
    event listeners to the list given below.</para>

    <table>
      <title>Hibernate Entity Manager default event listeners

      <tgroup cols="2">
        <colspec align="left" colname="c1" />

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

        <thead>
          <row>
            <entry>Event

            <entry>Listeners
          </row>
        </thead>

        <tbody>
          <row>
            <entry>flush

            <entry>org.hibernate.ejb.event.EJB3FlushEventListener
          </row>

          <row>
            <entry>auto-flush

            <entry>org.hibernate.ejb.event.EJB3AutoFlushEventListener
          </row>

          <row>
            <entry>delete

            <entry>org.hibernate.ejb.event.EJB3DeleteEventListener
          </row>

          <row>
            <entry>flush-entity

            <entry>org.hibernate.ejb.event.EJB3FlushEntityEventListener
          </row>

          <row>
            <entry>merge

            <entry>org.hibernate.ejb.event.EJB3MergeEventListener
          </row>

          <row>
            <entry>create

            <entry>org.hibernate.ejb.event.EJB3PersistEventListener
          </row>

          <row>
            <entry>create-onflush

            <entry>org.hibernate.ejb.event.EJB3PersistOnFlushEventListener
          </row>

          <row>
            <entry>save

            <entry>org.hibernate.ejb.event.EJB3SaveEventListener
          </row>

          <row>
            <entry>save-update

            <entry>org.hibernate.ejb.event.EJB3SaveOrUpdateEventListener
          </row>

          <row>
            <entry>pre-insert

            <entry>org.hibernate.secure.internal.JACCPreInsertEventListener
          </row>

          <row>
            <entry>pre-insert

            <entry>org.hibernate.secure.internal.JACCPreUpdateEventListener
          </row>

          <row>
            <entry>pre-delete

            <entry>org.hibernate.secure.internal.JACCPreDeleteEventListener
          </row>

          <row>
            <entry>pre-load

            <entry>org.hibernate.secure.internal.JACCPreLoadEventListener
          </row>

          <row>
            <entry>post-delete

            <entry>org.hibernate.ejb.event.EJB3PostDeleteEventListener
          </row>

          <row>
            <entry>post-insert

            <entry>org.hibernate.ejb.event.EJB3PostInsertEventListener
          </row>

          <row>
            <entry>post-load

            <entry>org.hibernate.ejb.event.EJB3PostLoadEventListener
          </row>

          <row>
            <entry>post-update

            <entry>org.hibernate.ejb.event.EJB3PostUpdateEventListener
          </row>
        </tbody>
      </tgroup>
    </table>

    <para>Note that the JACC*EventListeners are removed
    if the security is not enabled.</para>

    <para>You can configure the event listeners either through the properties
    (see <xref linkend="setup-configuration" />) or through the
    <methodname>ejb3configuration.getEventListeners() API.
  </section>

  <section>
    <title>Obtaining an EntityManager in a Java SE environment

    <para>An entity manager factory should be considered as an immutable
    configuration holder, it is defined to point to a single datasource and to
    map a defined set of entities. This is the entry point to create and
    manage <classname>EntityManagers. The
    <classname>Persistence class is bootstrap class to create an
    entity manager factory.</para>

    <programlisting language="JAVA" role="JAVA">// Use persistence.xml configuration
EntityManagerFactory emf = Persistence.createEntityManagerFactory("manager1")
EntityManager em = emf.createEntityManager(); // Retrieve an application managed entity manager
// Work with the EM
em.close();
...
emf.close(); //close at application end</programlisting>

    <para>An entity manager factory is typically create at application
    initialization time and closed at application end. It's creation is an
    expensive process. For those who are familiar with Hibernate, an entity
    manager factory is very much like a session factory. Actually, an entity
    manager factory is a wrapper on top of a session factory. Calls to the
    entityManagerFactory are thread safe.</para>

    <para>Thanks to the EntityManagerFactory, you can
    retrieve an extended entity manager. The extended entity manager keep the
    same persistence context for the lifetime of the entity manager: in other
    words, the entities are still managed between two transactions (unless you
    call <methodname>entityManager.clear() in between). You can
    see an entity manager as a small wrapper on top of an Hibernate
    session.</para>

    <para>TODO explains emf.createEntityManager(Map)
  </section>

  <section>
    <title>Various

    <para>Hibernate Entity Manager comes with Hibernate Validator configured
    out of the box. You don't have to override any event yourself. If you do
    not use Hibernate Validator annotations in your domain model, there will
    be no performance cost. For more information on Hibernate Validator,
    please refer to the Hibernate Annotations reference guide.</para>
  </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-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.