<?xml version='1.0' encoding='utf-8' ?>

<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
  ~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
  -->
<chapter xmlns="http://docbook.org/ns/docbook"
         xmlns:xi="http://www.w3.org/2001/XInclude">

    <title>Transactions and concurrency control</title>

    <section>
        <title>Defining Transaction</title>
        <para>
            It is important to understand that the term transaction has many different yet related meanings in regards
            to persistence and Object/Relational Mapping.  In most use-cases these definitions align, but that is not
            always the case.
        </para>
        <itemizedlist>
            <listitem>
                <para>
                    Might refer to the physical transaction with the database.
                </para>
            </listitem>
            <listitem>
                <para>
                    Might refer to the logical notion of a transaction as related to a persistence context.
                </para>
            </listitem>
            <listitem>
                <para>
                    Might refer to the application notion of a Unit-of-Work, as defined by the archetypal pattern.
                </para>
            </listitem>
        </itemizedlist>
        <note>
            <para>
                This documentation largely treats the physical and logic notions of transaction as one-in-the-same.
            </para>
        </note>
    </section>

    <section>
        <title>Physical Transactions</title>
        <para>
            Hibernate uses the JDBC API for persistence.  In the world of Java there are 2 well defined mechanism
            for dealing with transactions in JDBC: JDBC itself and JTA.  Hibernate supports both mechanisms for
            integrating with transactions and allowing applications to manage physical transactions.
        </para>
        <para>
            The first concept in understanding Hibernate transaction support is the
            <interfacename>org.hibernate.engine.transaction.spi.TransactionFactory</interfacename> interface which
            serves 2 main functions:
        </para>
        <itemizedlist>
            <listitem>
                <para>
                    It allows Hibernate to understand the transaction semantics of the environment.  Are we operating
                    in a JTA environment?  Is a physical transaction already currently active?  etc.
                </para>
            </listitem>
            <listitem>
                <para>
                    It acts as a factory for <interfacename>org.hibernate.Transaction</interfacename> instances which
                    are used to allow applications to manage and check the state of transactions.
                    <interfacename>org.hibernate.Transaction</interfacename> is Hibernate's notion of a logical
                    transaction.  JPA has a similar notion in the
                    <interfacename>javax.persistence.EntityTransaction</interfacename> interface.
                </para>
            </listitem>
        </itemizedlist>

        <note>
            <para>
                <interfacename>javax.persistence.EntityTransaction</interfacename> is only available when using
                resource-local transactions.  Hibernate allows access to
                <interfacename>org.hibernate.Transaction</interfacename> regardless of environment.
            </para>
        </note>

        <para>
            <interfacename>org.hibernate.engine.transaction.spi.TransactionFactory</interfacename> is a standard
            Hibernate service.  See <xref linkend="services-TransactionFactory"/> for details.
        </para>

        <section>
            <title>Physical Transactions - JDBC</title>
            <para>
                JDBC-based transaction management leverages the JDBC defined methods
                <methodname>java.sql.Connection.commit()</methodname> and
                <methodname>java.sql.Connection.rollback()</methodname> (JDBC does not define an explicit
                method of beginning a transaction).  In Hibernate, this approach is represented by the
                <classname>org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory</classname> class.
            </para>
        </section>

        <section>
            <title>Physical Transactions - JTA</title>
            <para>
                JTA-based transaction approach which leverages the
                <interfacename>javax.transaction.UserTransaction</interfacename> interface as obtained from
                <interfacename>org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform</interfacename> API.  This approach
                is represented by the
                <classname>org.hibernate.engine.transaction.internal.jta.JtaTransactionFactory</classname> class.
            </para>
            <para>
                See <xref linkend="services-JtaPlatform"/> for information on integration with the underlying JTA
                system.
            </para>
        </section>


        <section>
            <title>Physical Transactions - CMT</title>
            <para>
                Another JTA-based transaction approach which leverages the JTA
                <interfacename>javax.transaction.TransactionManager</interfacename> interface as obtained from
                <interfacename>org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform</interfacename> API.  This approach
                is represented by the
                <classname>org.hibernate.engine.transaction.internal.jta.CMTTransactionFactory</classname> class.  In
                an actual JEE CMT environment, access to the
                <interfacename>javax.transaction.UserTransaction</interfacename> is restricted.
            </para>
            <note>
                <para>
                    The term CMT is potentially misleading here.  The important point simply being that the physical JTA
                    transactions are being managed by something other than the Hibernate transaction API.
                </para>
            </note>
            <para>
                See <xref linkend="services-JtaPlatform"/> for information on integration with the underlying JTA
                system.
            </para>
        </section>

        <section>
            <title>Physical Transactions - Custom</title>
            <para>
                Its is also possible to plug in a custom transaction approach by implementing the
                <interfacename>org.hibernate.engine.transaction.spi.TransactionFactory</interfacename> contract.
                The default service initiator has built-in support for understanding custom transaction approaches
                via the <literal>hibernate.transaction.factory_class</literal> which can name either:
            </para>
            <itemizedlist>
                <listitem>
                    <para>
                        The instance of <interfacename>org.hibernate.engine.transaction.spi.TransactionFactory</interfacename>
                        to use.
                    </para>
                </listitem>
                <listitem>
                    <para>
                        The name of a class implementing
                        <interfacename>org.hibernate.engine.transaction.spi.TransactionFactory</interfacename>
                        to use.  The expectation is that the implementation class have a no-argument constructor.
                    </para>
                </listitem>
            </itemizedlist>
        </section>

        <section>
            <title>Physical Transactions - Legacy</title>
            <para>
                During development of 4.0, most of these classes named here were moved to new packages.  To help
                facilitate upgrading, Hibernate will also recognize the legacy names here for a short period of time.
            </para>
            <itemizedlist>
                <listitem>
                    <para>
                        <literal>org.hibernate.transaction.JDBCTransactionFactory</literal> is mapped to
                        <classname>org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory</classname>
                    </para>
                </listitem>
                <listitem>
                    <para>
                        <literal>org.hibernate.transaction.JTATransactionFactory</literal> is mapped to
                        <classname>org.hibernate.engine.transaction.internal.jta.JtaTransactionFactory</classname>
                    </para>
                </listitem>
                <listitem>
                    <para>
                        <literal>org.hibernate.transaction.CMTTransactionFactory</literal> is mapped to
                        <classname>org.hibernate.engine.transaction.internal.jta.CMTTransactionFactory</classname>
                    </para>
                </listitem>
            </itemizedlist>
        </section>

    </section>


    <section>
        <title>Hibernate Transaction Usage</title>
        <para>
            Hibernate uses JDBC connections and JTA resources directly, without adding any additional locking behavior.
            It is important for you to become familiar with the JDBC, ANSI SQL, and transaction isolation specifics
            of your database management system.
        </para>
        <para>
            Hibernate does not lock objects in memory.  The behavior defined by the isolation level of your database
            transactions does not change when you use Hibernate.  The Hibernate
            <interfacename>org.hibernate.Session</interfacename> acts as a transaction-scoped cache providing
            repeatable reads for lookup by identifier and queries that result in loading entities.
        </para>

        <important>
            <para>
                To reduce lock contention in the database, the physical database transaction needs to be as short as
                possible.  Long database transactions prevent your application from scaling to a highly-concurrent load.
                Do not hold a database transaction open during end-user-level work, but open it after the end-user-level
                work is finished.  This is concept is referred to as <literal>transactional write-behind</literal>.
            </para>
        </important>
    </section>

    <section>
        <title>Transactional patterns (and anti-patterns)</title>

        <section xml:id="session-per-operation">
            <title>Session-per-operation anti-pattern</title>
            <para>
                This is an anti-pattern of opening and closing a <classname>Session</classname> for each database call
                in a single thread.  It is also an anti-pattern in terms of database transactions. Group your database
                calls into a planned sequence.  In the same way, do not auto-commit after every SQL statement in your
                application.  Hibernate disables, or expects the application server to disable, auto-commit mode
                immediately.  Database transactions are never optional.  All communication with a database must
                be encapsulated by a transaction.  Avoid auto-commit behavior for reading data, because many small
                transactions are unlikely to perform better than one clearly-defined unit of work, and are more
                difficult to maintain and extend.
            </para>
            <note>
                <para>
                    Using auto-commit does not circumvent database transactions.  Instead, when in auto-commit mode,
                    JDBC drivers simply perform each call in an implicit transaction call.  It is as if your application
                    called commit after each and every JDBC call.
                </para>
            </note>
        </section>

        <section xml:id="session-per-request">
            <title>Session-per-request pattern</title>
            <para>
                This is the most common transaction pattern.  The term request here relates to the concept of a system
                that reacts to a series of requests from a client/user.  Web applications are a prime example of this
                type of system, though certainly not the only one.  At the beginning of handling such a request, the
                application opens a Hibernate <interfacename>Session</interfacename>, starts a transaction, performs
                all data related work, ends the transaction and closes the <interfacename>Session</interfacename>.
                The crux of the pattern is the one-to-one relationship between the transaction and the
                <interfacename>Session</interfacename>.
            </para>

            <para>
                Within this pattern there is a common technique of defining a <firstterm>current session</firstterm> to
                simplify the need of passing this <interfacename>Session</interfacename> around to all the application
                components that may need access to it.  Hibernate provides support for this technique through the
                <methodname>getCurrentSession</methodname> method of the <interfacename>SessionFactory</interfacename>.
                The concept of a "current" session has to have a scope that defines the bounds in which the notion
                of "current" is valid.   This is purpose of the
                <interfacename>org.hibernate.context.spi.CurrentSessionContext</interfacename> contract.  There are 2
                reliable defining scopes:
            </para>
            <itemizedlist>
                <listitem>
                    <para>
                        First is a JTA transaction because it allows a callback hook to know when it is ending which
                        gives Hibernate a chance to close the <interfacename>Session</interfacename> and clean up.
                        This is represented by the
                        <classname>org.hibernate.context.internal.JTASessionContext</classname> implementation of
                        the <interfacename>org.hibernate.context.spi.CurrentSessionContext</interfacename> contract.
                        Using this implementation, a <interfacename>Session</interfacename> will be opened the first
                        time <methodname>getCurrentSession</methodname> is called within that transaction.
                    </para>
                </listitem>
                <listitem>
                    <para>
                        Secondly is this application request cycle itself.  This is best represented with the
                        <classname>org.hibernate.context.internal.ManagedSessionContext</classname> implementation of
                        the <interfacename>org.hibernate.context.spi.CurrentSessionContext</interfacename> contract.
                        Here an external component is responsible for managing the lifecycle and scoping of a "current"
                        session.  At the start of such a scope, <classname>ManagedSessionContext</classname>'s
                        <methodname>bind</methodname> method is called passing in the
                        <interfacename>Session</interfacename>.  At the end, its <methodname>unbind</methodname>
                        method is called.
                    </para>
                    <para>
                        Some common examples of such "external components" include:
                    </para>
                    <itemizedlist>
                        <listitem>
                            <para>
                                <interfacename>javax.servlet.Filter</interfacename> implementation
                            </para>
                        </listitem>
                        <listitem>
                            <para>
                                AOP interceptor with a pointcut on the service methods
                            </para>
                        </listitem>
                        <listitem>
                            <para>
                                A proxy/interception container
                            </para>
                        </listitem>
                    </itemizedlist>
                </listitem>
            </itemizedlist>
            <important>
                <para>
                    The <methodname>getCurrentSession()</methodname> method has one downside in a JTA environment.  If
                    you use it, after_statement connection release mode is also used by default.  Due to a limitation of
                    the JTA specification, Hibernate cannot automatically clean up any unclosed
                    <interfacename>ScrollableResults</interfacename> or <interfacename>Iterator</interfacename>
                    instances returned by <methodname>scroll()</methodname> or <methodname>iterate()</methodname>.
                    Release the underlying database cursor by calling <methodname>ScrollableResults.close()</methodname>
                    or <methodname>Hibernate.close(Iterator)</methodname> explicitly from a
                    <systemitem>finally</systemitem> block.
                </para>
            </important>
        </section>

        <section xml:id="long-conversations">
            <title>Conversations</title>
            <para>
                The <phrase>session-per-request</phrase> pattern is not the only valid way of designing units of work.
                Many business processes require a whole series of interactions with the user that are interleaved with
                database accesses. In web and enterprise applications, it is not acceptable for a database transaction
                to span a user interaction. Consider the following example:
            </para>
            <procedure>
                <title>An example of a long-running conversation</title>
                <step>
                    <para>
                        The first screen of a dialog opens. The data seen by the user is loaded in a particular
                        <classname>Session</classname> and database transaction.  The user is free to modify the objects.
                    </para>
                </step>
                <step>
                    <para>
                        The user uses a UI element to save their work after five minutes of editing. The modifications
                        are made persistent.  The user also expects to have exclusive access to the data during the edit
                        session.
                    </para>
                </step>
            </procedure>

            <para>
                Even though we have multiple databases access here, from the point of view of the user, this series of
                steps represents a single unit of work.  There are many ways to implement this in your application.
            </para>

            <para>
                A first naive implementation might keep the <classname>Session</classname> and database transaction open
                while the user is editing, using database-level locks to prevent other users from modifying the same
                data and to guarantee isolation and atomicity.  This is an anti-pattern, because lock contention is a
                bottleneck which will prevent scalability in the future.
            </para>
            <para>
                Several database transactions are used to implement the conversation.  In this case, maintaining
                isolation of business processes becomes the partial responsibility of the application tier.  A single
                conversation usually spans several database transactions.  These multiple database accesses can only
                be atomic as a whole if only one of these database transactions (typically the last one) stores the
                updated data.  All others only read data.  A common way to receive this data is through a wizard-style
                dialog spanning several request/response cycles.  Hibernate includes some features which make this easy
                to implement.
            </para>

            <informaltable>
                <tgroup cols="2">
                    <tbody>
                        <row>
                            <entry>
                                <para>
                                    Automatic Versioning
                                </para>
                            </entry>
                            <entry>
                                <para>
                                    Hibernate can perform automatic optimistic concurrency control for you.  It can
                                    automatically detect if a concurrent modification occurred during user think time.
                                    Check for this at the end of the conversation.
                                </para>
                            </entry>
                        </row>
                        <row>
                            <entry>
                                <para>
                                    Detached Objects
                                </para>
                            </entry>
                            <entry>
                                <para>
                                    If you decide to use the session-per-request pattern, all loaded instances will be
                                    in the detached state during user think time.  Hibernate allows you to reattach the
                                    objects and persist the modifications.  The pattern is called
                                    session-per-request-with-detached-objects.  Automatic versioning is used to isolate
                                    concurrent modifications.
                                </para>
                            </entry>
                        </row>
                        <row>
                            <entry>
                                <para>
                                    Extended Session
                                </para>
                            </entry>
                            <entry>
                                <para>
                                    The Hibernate <interfacename>Session</interfacename> can be disconnected from the
                                    underlying JDBC connection after the database transaction has been committed and
                                    reconnected when a new client request occurs. This pattern is known as
                                    session-per-conversation and makes even reattachment unnecessary. Automatic
                                    versioning is used to isolate concurrent modifications and the
                                    <interfacename>Session</interfacename> will not be allowed to flush automatically,
                                    only explicitly.
                                </para>
                            </entry>
                        </row>
                    </tbody>
                </tgroup>
            </informaltable>

            <para>
                <phrase>Session-per-request-with-detached-objects</phrase> and <phrase>session-per-conversation</phrase>
                each have advantages and disadvantages.
            </para>
        </section>

        <section>
            <title>Session-per-application</title>
            <para>
                Discussion coming soon..
            </para>
        </section>
    </section>

    <section>
        <title>Object identity</title>
        <para>
            An application can concurrently access the same persistent state (database row) in two different Sessions.
            However, an instance of a persistent class is never shared between two
            <interfacename>Session</interfacename> instances.  Two different notions of identity exist and come into
            play here: Database identity and JVM identity.
        </para>
        <example>
            <title>Database identity</title>
            <programlisting language="Java" role="JAVA"><xi:include href="extras/database-identity.java" parse="text" /></programlisting>
        </example>
        <example>
            <title>JVM identity</title>
            <programlisting language="Java" role="JAVA"><xi:include href="extras/jvm-identity.java" parse="text" /></programlisting>
        </example>
        <para>
            For objects attached to a particular <interfacename>Session</interfacename>, the two notions are
            equivalent, and JVM identity for database identity is guaranteed by Hibernate.  The application might
            concurrently access a business object with the same identity in two different sessions, the two
            instances are actually different, in terms of JVM identity.  Conflicts are resolved using an optimistic
            approach and automatic versioning at flush/commit time.
        </para>
        <para>
            This approach places responsibility for concurrency on Hibernate and the database. It also provides the
            best scalability, since expensive locking is not needed to guarantee identity in single-threaded units
            of work.  The application does not need to synchronize on any business object, as long as it maintains
            a single thread per anti-patterns.  While not recommended, within a
            <interfacename>Session</interfacename> the application could safely use the <literal>==</literal>
            operator to compare objects.
        </para>
        <para>

            However, an application that uses the <literal>==</literal> operator outside of a
            <interfacename>Session</interfacename>
    may introduce problems.. If you put two detached instances into the same <classname>Set</classname>, they might
    use the same database identity, which means they represent the same row in the database. They would not be
    guaranteed to have the same JVM identity if they are in a detached state. Override the
    <methodname>equals</methodname> and <methodname>hashCode</methodname> methods in persistent classes, so that
    they have their own notion of object equality. Never use the database identifier to implement equality. Instead,
    use a business key that is a combination of unique, typically immutable, attributes. The database identifier
    changes if a transient object is made persistent. If the transient instance, together with detached instances,
    is held in a <classname>Set</classname>, changing the hash-code breaks the contract of the
    <classname>Set</classname>. Attributes for business keys can be less stable than database primary keys. You only
    need to guarantee stability as long as the objects are in the same <classname>Set</classname>.This is not a
    Hibernate issue, but relates to Java's implementation of object identity and equality.
  </para>

</section>


    <section xml:id="transactions-basics-issues">
        <title>Common issues</title>

         <para>
             Both the <emphasis>session-per-user-session</emphasis> and <emphasis>session-per-application</emphasis>
             anti-patterns are susceptible to the following issues.  Some of the issues might also arise within the
             recommended patterns, so ensure that you understand the implications before making a design decision:
         </para>

        <itemizedlist>
            <listitem>
                <para>
                    A <interfacename>Session</interfacename> is not thread-safe. Things that work concurrently, like
                    HTTP requests, session beans, or Swing workers, will cause race conditions if a
                    <interfacename>Session</interfacename> instance is shared. If you keep your Hibernate
                    <interfacename>Session</interfacename> in your
                    <interfacename>javax.servlet.http.HttpSession</interfacename> (this is discussed later in the
                    chapter), you should consider synchronizing access to your
                    <interfacename>HttpSession</interfacename>; otherwise, a user that clicks reload fast enough can use
                    the same <interfacename>Session</interfacename> in two concurrently running threads.
                </para>
            </listitem>
            <listitem>
                <para>
                    An exception thrown by Hibernate means you have to rollback your database transaction
                    and close the <interfacename>Session</interfacename> immediately (this is discussed in more detail
                    later in the chapter).  If your <interfacename>Session</interfacename> is bound to the application,
                    you have to stop the application.  Rolling back the database transaction does not put your business
                    objects back into the state they were at the start of the transaction.  This means that the
                    database state and the business objects will be out of sync. Usually this is not a
                    problem, because exceptions are not recoverable and you will have to start over after
                    rollback anyway.
                </para>
            </listitem>
            <listitem>
                <para>
                    The <interfacename>Session</interfacename> caches every object that is in a persistent state
                    (watched and checked for changes by Hibernate).  If you keep it open for a long time or simply load
                    too much data, it will grow endlessly until you get an OutOfMemoryException.  One solution is to
                    call <methodname>clear()</methodname> and <methodname>evict()</methodname> to manage the
                    <interfacename>Session</interfacename> cache, but you should consider an alternate means of dealing
                    with large amounts of data such as a Stored Procedure.  Java is simply not the right tool for these
                    kind of operations.  Some solutions are shown in <xref linkend="batch"/>.  Keeping a
                    <interfacename>Session</interfacename> open for the duration of a user session also means a higher
                    probability of stale data.
                </para>
            </listitem>
        </itemizedlist>

    </section>

</chapter>
