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

Hibernate example source code file (Batch_Processing.xml)

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

hibernate, hibernate, hql, hql, if, in, insert, java, java, jdbc, the, the, update, you

The Hibernate Batch_Processing.xml source code

<?xml version='1.0' encoding='utf-8' ?>
<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
<!ENTITY % BOOK_ENTITIES SYSTEM "Hibernate_Development_Guide.ent">
%BOOK_ENTITIES;
]>
<chapter>
  <title>Batch Processing
  <para>
    The following example shows an antipattern for batch inserts.
  </para>
  <example>
    <title>Naive way to insert 100000 lines with Hibernate
    <programlisting language="Java" role="JAVA">
    <para>
      This fails with exception <systemitem>OutOfMemoryException after around 50000 rows on most
      systems. The reason is that Hibernate caches all the newly inserted Customer instances in the session-level
      cache. There are several ways to avoid this problem.
    </para>
  </example>
  <para>
    Before batch processing, enable JDBC batching. To enable JDBC batching, set the property
    <property>hibernate.jdbc.batch_size to an integer between 10 and 50.
  </para>
  <note>
    <para>
      Hibernate disables insert batching at the JDBC level transparently if you use an identity identifier generator.
    </para>
  </note>
  <para>
    If the above approach is not appropriate, you can disable the second-level cache, by setting
    <property>hibernate.cache.use_second_level_cache to false.
  </para>
  
  <section>
    <title>Batch inserts
    <para>
      When you make new objects persistent, employ methods <methodname>flush() and
      <methodname>clear() to the session regularly, to control the size of the first-level cache.
    </para>
    <example>
      <title>Flushing and clearing the Session
      <programlisting language="Java" role="JAVA">
    </example>
  </section>
  
  <section>
    <title>Batch updates
    <para>
      When you retriev and update data, <methodname>flush() and clear() the
      session regularly.  In addition, use method <methodname>scroll() to take advantage of server-side
      cursors for queries that return many rows of data.
    </para>
    <example>
      <title>Using scroll()
      <programlisting language="Java" role="JAVA">
    </example>
  </section>
  
  <section>
    <title>StatelessSession
    <para>
      <interfacename>StatelessSession is a command-oriented API provided by Hibernate. Use it to stream
      data to and from the database in the form of detached objects. A <interfacename>StatelessSession
      has no persistence context associated with it and does not provide many of the higher-level life cycle
      semantics. Some of the things not provided by a <interfacename>StatelessSession include:
    </para>
    <itemizedlist>
      <title>Features and behaviors not provided by StatelessSession
      <listitem>
        <para>
          a first-level cache
        </para>
      </listitem>
      <listitem>
        <para>
          interaction with any second-level or query cache
        </para>
      </listitem>
      <listitem>
        <para>
          transactional write-behind or automatic dirty checking
        </para>
      </listitem>
    </itemizedlist>
    <itemizedlist>
      <title>Limitations of StatelessSession
      <listitem>
        <para>
          Operations performed using a stateless session never cascade to associated instances.
        </para>
      </listitem>
      <listitem>
        <para>
          Collections are ignored by a stateless session.
        </para>
      </listitem>
      <listitem>
        <para>
          Operations performed via a stateless session bypass Hibernate's event model and interceptors.
        </para>
      </listitem>
      <listitem>
        <para>
          Due to the lack of a first-level cache, Stateless sessions are vulnerable to data aliasing effects.
        </para>
      </listitem>
      <listitem>
        <para>
          A stateless session is a lower-level abstraction that is much closer to the underlying JDBC.
        </para>
      </listitem>
    </itemizedlist>
    <example>
      <title>Using a StatelessSession
      <programlisting language="Java" role="JAVA">
      <para>
        The <classname>Customer instances returned by the query are immediately detached. They are never
        associated with any persistence context.
      </para>
    </example>
    <para>
      The <methodname>insert(), update(), and delete()
      operations defined by the <interfacename>StatelessSession interface operate directly on database
      rows. They cause the corresponding SQL operations to be executed immediately.  They have different semantics from
      the <methodname>save(), saveOrUpdate(), and
      <methodname>delete() operations defined by the Session interface.
    </para>
  </section>
  
  <section>
    <title>Hibernate Query Language for DML
    <para>
      DML, or <firstterm>Data Markup Language, refers to SQL statements such as INSERT,
      <literal>UPDATE, and DELETE. Hibernate provides methods for bulk SQL-style DML
      statement execution, in the form of <firstterm>Hibernate Query Language (HQL).
    </para>
    <section>
      <title>HQL for UPDATE and DELETE
      <example>
        <title>Psuedo-syntax for UPDATE and DELETE statements using HQL
        <screen>
          ( UPDATE | DELETE ) FROM? EntityName (WHERE where_conditions)?
        </screen>
        <para>
          The <literal>? suffix indications an optional parameter. The FROM and
          <literal>WHERE clauses are each optional.
        </para>
      </example>
      <para>
        The <literal>FROM clause can only refer to a single entity, which can be aliased. If the entity name
        is aliased, any property references must be qualified using that alias. If the entity name is not aliased, then
        it is illegal for any property references to be qualified.
      </para>
      <para>
        Joins, either implicit or explicit, are prohibited in a bulk HQL query. You can use sub-queries in the
        <literal>WHERE clause, and the sub-queries themselves can contain joins.
      </para>
      <example>
        <title>Executing an HQL UPDATE, using the Query.executeUpdate() method
        <programlisting language="Java" role="JAVA">
      </example>
      <para>
        In keeping with the EJB3 specification, HQL UPDATE statements, by default, do not effect the version or the
        timestamp property values for the affected entities. You can use a versioned update to force Hibernate to reset
        the version or timestamp property values, by adding the <literal>VERSIONED keyword after the
        <literal>UPDATE keyword.
      </para>
      <example>
        <title>Updating the version of timestamp
        <programlisting language="Java" role="JAVA">
      </example>
      <note>
        <para>
          If you use the <literal>VERSIONED statement, you cannot use custom version types, which use class
          <classname>org.hibernate.usertype.UserVersionType.
        </para>
      </note>
      <example>
        <title>A HQL DELETE statement
        <programlisting language="Java" role="JAVA">
      </example>
      <para>
        Method <methodname>Query.executeUpdate() returns an int value, which indicates the
        number of entities effected by the operation. This may or may not correlate to the number of rows effected in
        the database. An HQL bulk operation might result in multiple SQL statements being executed, such as for
        joined-subclass. In the example of joined-subclass, a <literal>DELETE against one of the subclasses
        may actually result in deletes in the tables underlying the join, or further down the inheritance hierarchy.
      </para>
    </section>
    
    <section>
      <title>HQL syntax for INSERT
      <example>
        <title>Pseudo-syntax for INSERT statements
        <screen>
          INSERT INTO EntityName <replaceable>properties_list select_statement
        </screen>
      </example>
      <para>
        Only the <literal>INSERT INTO ... SELECT ... form is supported. You cannot specify explicit values to
        insert.
      </para>
      <para>
        The <replaceable>properties_list is analogous to the column specification in the SQL
        INSERT</literal> statement. For entities involved in mapped inheritance, you can only use properties directly
        defined on that given class-level in the <replaceable>properties_list. Superclass properties are
        not allowed and subclass properties are irrelevant. In other words, <literal>INSERT statements are
        inherently non-polymorphic.
      </para>
      <para>
        The <replaceable>select_statement can be any valid HQL select query, but the return types must
        match the types expected by the INSERT. Hibernate verifies the return types during query compilation, instead of
        expecting the database to check it. Problems might result from Hibernate types which are equivalent, rather than
        equal. One such example is a mismatch between a property defined as an <type>org.hibernate.type.DateType
        and a property defined as an <type>org.hibernate.type.TimestampType, even though the database may not
        make a distinction, or may be capable of handling the conversion.
      </para>
      <para>
        If <replaceable>id property is not specified in the properties_list,
        Hibernate generates a value automatically. Automatic generation is only available if you use ID generators which
        operate on the database. Otherwise, Hibernate throws an exception during parsing. Available in-database
        generators are <classname>org.hibernate.id.SequenceGenerator and its subclasses, and objects which
        implement <interfacename>org.hibernate.id.PostInsertIdentifierGenerator. The most notable
        exception is <classname>org.hibernate.id.TableHiLoGenerator, which does not expose a selectable way
        to get its values.
      </para>
      <para>
        For properties mapped as either version or timestamp, the insert statement gives you two options. You can either
        specify the property in the properties_list, in which case its value is taken from the corresponding select
        expressions, or omit it from the properties_list, in which case the seed value defined by the
        org.hibernate.type.VersionType is used.
      </para>
      <example>
        <title>HQL INSERT statement
        <programlisting language="Java" role="JAVA">
      </example>
    </section>
    <section>
      <title>More information on HQL
      <para>
        This section is only a brief overview of HQL. For more information, see <xref linkend="chap-hql" />.
      </para>
    </section>
  </section>
</chapter>

Other Hibernate examples (source code examples)

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