<?xml version='1.0' encoding="UTF-8"?>
<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ Copyright (c) 2010, 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" [
<!ENTITY % BOOK_ENTITIES SYSTEM "../HIBERNATE_-_Relational_Persistence_for_Idiomatic_Java.ent">
%BOOK_ENTITIES;

]>

<chapter id="architecture">

    <title>Architecture</title>

    <section id="architecture-overview">
        <title>Overview</title>
        
        <para>
            The diagram below provides a high-level view of the Hibernate architecture:
        </para>

        <mediaobject>
            <imageobject role="fo">
                <imagedata fileref="images/overview.svg" format="SVG" align="center"/>
            </imageobject>
            <imageobject role="html">
                <imagedata fileref="images/overview.png" format="PNG" align="center"/>
            </imageobject>
        </mediaobject>

        <para>
            Unfortunately we cannot provide a detailed view of all possible runtime architectures.  Hibernate is
            sufficiently flexible to be used in a number of ways in many, many architectures.  We will, however,
            illustrate 2 specifically since they are extremes.
        </para>

        <section id="architecture-overview-minimal">
            <title>Minimal architecture</title>

            <para>
                The "minimal" architecture has the application manage its own JDBC connections and provide those
                connections to Hibernate; additionally the application manages transactions for itself.  This approach
                uses a minimal subset of Hibernate APIs.
            </para>
            <mediaobject>
                <imageobject role="fo">
                    <imagedata fileref="images/lite.svg" format="SVG" align="center"/>
                </imageobject>
                <imageobject role="html">
                    <imagedata fileref="images/lite.png" format="PNG" align="center"/>
                </imageobject>
            </mediaobject>
        </section>

        <section id="architecture-overview-comprehensive">
            <title>Comprehensive architecture</title>

            <para>
                The "comprehensive" architecture abstracts the application away from the underlying JDBC/JTA APIs and
                allows Hibernate to manage the details.
            </para>
            <mediaobject>
                <imageobject role="fo">
                    <imagedata fileref="images/full_cream.svg" format="SVG" align="center"/>
                </imageobject>
                <imageobject role="html">
                    <imagedata fileref="images/full_cream.png" format="PNG" align="center"/>
                </imageobject>
            </mediaobject>
        </section>

        <section id="architecture-overview-terms">
            <title>Basic APIs</title>
            <para>
                Here are quick discussions about some of the API objects depicted in the preceding diagrams (you will
                see them again in more detail in later chapters).
                <variablelist spacing="compact">
                    <varlistentry>
                        <term>SessionFactory (<interfacename>org.hibernate.SessionFactory</interfacename>)</term>
                        <listitem>
                            <para>
                                A thread-safe, immutable cache of compiled mappings for a single database.
                                A factory for <interfacename>org.hibernate.Session</interfacename> instances.  A client
                                of <interfacename>org.hibernate.connection.ConnectionProvider</interfacename>.  Optionally
                                maintains a <literal>second level cache</literal> of data that is reusable between
                                transactions at a process or cluster level.
                            </para>
                        </listitem>
                    </varlistentry>
                    <varlistentry>
                        <term>Session (<interfacename>org.hibernate.Session</interfacename>)</term>
                        <listitem>
                            <para>
                                A single-threaded, short-lived object representing a conversation between
                                the application and the persistent store.  Wraps a JDBC
                                <interfacename>java.sql.Connection</interfacename>.  Factory for
                                <interfacename>org.hibernate.Transaction</interfacename>.  Maintains a
                                <literal>first level cache</literal> of persistent the application's persistent objects
                                and collections; this cache is used when navigating the object graph or looking up
                                objects by identifier.
                            </para>
                        </listitem>
                    </varlistentry>
                    <varlistentry>
                        <term>Persistent objects and collections</term>
                        <listitem>
                            <para>
                                Short-lived, single threaded objects containing persistent state and business
                                function.  These can be ordinary JavaBeans/POJOs. They are associated with exactly one
                                <interfacename>org.hibernate.Session</interfacename>. Once the
                                <interfacename>org.hibernate.Session</interfacename> is closed, they will be detached
                                and free to use in any application layer (for example, directly as data transfer objects
                                to and from presentation).  <xref linkend="objectstate"/> discusses transient,
                                persistent and detached object states.
                            </para>
                        </listitem>
                    </varlistentry>
                    <varlistentry>
                        <term>Transient and detached objects and collections</term>
                        <listitem>
                            <para>
                                Instances of persistent classes that are not currently associated with a
                                <interfacename>org.hibernate.Session</interfacename>. They may have been instantiated by
                                the application and not yet persisted, or they may have been instantiated by a
                                closed <interfacename>org.hibernate.Session</interfacename>.
                                <xref linkend="objectstate"/> discusses transient, persistent and detached object states.
                            </para>
                        </listitem>
                    </varlistentry>
                    <varlistentry>
                        <term>Transaction (<interfacename>org.hibernate.Transaction</interfacename>)</term>
                        <listitem>
                            <para>
                                (Optional) A single-threaded, short-lived object used by the application to
                                specify atomic units of work. It abstracts the application from the underlying JDBC,
                                JTA or CORBA transaction. A <interfacename>org.hibernate.Session</interfacename> might span several
                                <interfacename>org.hibernate.Transaction</interfacename>s in some cases. However,
                                transaction demarcation, either using the underlying API or
                                <interfacename>org.hibernate.Transaction</interfacename>, is never optional.
                            </para>
                        </listitem>
                    </varlistentry>
                    <varlistentry>
                        <term>ConnectionProvider (<interfacename>org.hibernate.connection.ConnectionProvider</interfacename>)</term>
                        <listitem>
                            <para>
                                (Optional) A factory for, and pool of, JDBC connections. It abstracts the application from
                                underlying <interfacename>javax.sql.DataSource</interfacename> or
                                <interfacename>java.sql.DriverManager</interfacename>.  It is not exposed to application,
                                but it can be extended and/or implemented by the developer.
                            </para>
                        </listitem>
                    </varlistentry>
                    <varlistentry>
                        <term>TransactionFactory (<interfacename>org.hibernate.TransactionFactory</interfacename>)</term>
                        <listitem>
                            <para>
                                (Optional) A factory for <interfacename>org.hibernate.Transaction</interfacename>
                                instances. It is not exposed to the application, but it can be extended and/or
                                implemented by the developer.
                            </para>
                        </listitem>
                    </varlistentry>
                    <varlistentry>
                        <term><emphasis>Extension Interfaces</emphasis></term>
                        <listitem>
                            <para>
                                Hibernate offers a range of optional extension interfaces you can implement to customize
                                the behavior of your persistence layer. See the API documentation for details.
                            </para>
                        </listitem>
                    </varlistentry>
                </variablelist>
            </para>
        </section>
    </section>

    <section id="architecture-jmx" revision="1">
        <title>JMX Integration</title>

        <para>
            JMX is the J2EE standard for the management of Java components. Hibernate can be managed via
            a JMX standard service. AN MBean implementation is provided in the distribution:
            <literal>org.hibernate.jmx.HibernateService</literal>.
        </para>

        <para>
            Another feature available as a JMX service is runtime Hibernate statistics. See
            <xref linkend="configuration-optional-statistics"/> for more information.
        </para>
    </section>

    <section id="architecture-current-session" revision="2">
        <title>Contextual sessions</title>
        <para>
            Most applications using Hibernate need some form of "contextual" session, where a given
            session is in effect throughout the scope of a given context. However, across applications
            the definition of what constitutes a context is typically different; different contexts
            define different scopes to the notion of current. Applications using Hibernate prior
            to version 3.0 tended to utilize either home-grown <literal>ThreadLocal</literal>-based
            contextual sessions, helper classes such as <literal>HibernateUtil</literal>, or utilized
            third-party frameworks, such as Spring or Pico, which provided proxy/interception-based contextual sessions.
        </para>
        <para>
            Starting with version 3.0.1, Hibernate added the <literal>SessionFactory.getCurrentSession()</literal>
            method. Initially, this assumed usage of <literal>JTA</literal> transactions, where the
            <literal>JTA</literal> transaction defined both the scope and context of a current session.
            Given the maturity of the numerous stand-alone
            <literal>JTA TransactionManager</literal> implementations, most, if not all,
            applications should be using <literal>JTA</literal> transaction management, whether or not
            they are deployed into a <literal>J2EE</literal> container.  Based on that, the
            <literal>JTA</literal>-based contextual sessions are all you need to use.
        </para>
        <para>
            However, as of version 3.1, the processing behind
            <literal>SessionFactory.getCurrentSession()</literal> is now pluggable.  To that
            end, a new extension interface, <literal>org.hibernate.context.CurrentSessionContext</literal>,
            and a new configuration parameter, <literal>hibernate.current_session_context_class</literal>,
            have been added to allow pluggability of the scope and context of defining current sessions.
        </para>
        <para>
            See the Javadocs for the <literal>org.hibernate.context.CurrentSessionContext</literal>
            interface for a detailed discussion of its contract.  It defines a single method,
            <literal>currentSession()</literal>, by which the implementation is responsible for
            tracking the current contextual session.  Out-of-the-box, Hibernate comes with three
            implementations of this interface:
        </para>

        <itemizedlist>
            <listitem>
                <para>
                    <literal>org.hibernate.context.JTASessionContext</literal>: current sessions
                    are tracked and scoped by a <literal>JTA</literal> transaction.  The processing
                    here is exactly the same as in the older JTA-only approach.  See the Javadocs
                    for details.
                </para>
            </listitem>
            <listitem>
                <para>
                    <literal>org.hibernate.context.ThreadLocalSessionContext</literal>:current
                    sessions are tracked by thread of execution. See the Javadocs for details.
                </para>
            </listitem>
            <listitem>
                <para>
                    <literal>org.hibernate.context.ManagedSessionContext</literal>: current
                    sessions are tracked by thread of execution. However, you are responsible to
                    bind and unbind a <literal>Session</literal> instance with static methods
                    on this class: it does not open, flush, or close a <literal>Session</literal>.
                </para>
            </listitem>
        </itemizedlist>

        <para>
            The first two implementations provide a "one session - one database transaction" programming
            model. This is also known and used as <emphasis>session-per-request</emphasis>. The beginning
            and end of a Hibernate session is defined by the duration of a database transaction.
            If you use programmatic transaction demarcation in plain JSE without JTA, you are advised to
            use the Hibernate <literal>Transaction</literal> API to hide the underlying transaction system
            from your code. If you use JTA, you can utilize the JTA interfaces to demarcate transactions. If you
            execute in an EJB container that supports CMT, transaction boundaries are defined declaratively
            and you do not need any transaction or session demarcation operations in your code.
            Refer to <xref linkend="transactions"/> for more information and code examples.
        </para>

        <para>
            The <literal>hibernate.current_session_context_class</literal> configuration parameter
            defines which <literal>org.hibernate.context.CurrentSessionContext</literal> implementation
            should be used.  For backwards compatibility, if this configuration parameter is not set
            but a <literal>org.hibernate.transaction.TransactionManagerLookup</literal> is configured,
            Hibernate will use the <literal>org.hibernate.context.JTASessionContext</literal>.
            Typically, the value of this parameter would just name the implementation class to
            use. For the three out-of-the-box implementations, however, there are three corresponding
            short names: "jta", "thread", and "managed".
        </para>
        
    </section>

</chapter>

