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

Hibernate example source code file (Caching.xml)

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

for, hibernate, in, in, it, java, java, session, the, the, this, this, to, you

The Hibernate Caching.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>Caching


  <section>
    <title>The query cache
    <para>
      If you have queries that run over and over, with the same parameters, query caching provides performance gains.
    </para>
    <para>
      Caching introduces overhead in the area of transactional processing. For example, if you cache results of a query
      against an object, Hibernate needs to keep track of whether any changes have been committed against the object,
      and invalidate the cache accordingly. In addition, the benefit from caching query results is limited, and highly
      dependent on the usage patterns of your application. For these reasons, Hibernate disables the query cache by
      default.
    </para>
    <procedure>
      <title>Enabling the query cache
      <step>
        <title>Set the hibernate.cache.use_query_cache property to true.
        <para>
          This setting creates two new cache regions:
        </para>
        <itemizedlist>
          <listitem>
            <para>
              <code>org.hibernate.cache.internal.StandardQueryCache holds the cached query results.
            </para>
          </listitem>
          <listitem>
            <para>
              <code>org.hibernate.cache.spi.UpdateTimestampsCache holds timestamps of the most recent updates to
              queryable tables. These timestamps validate results served from the query cache.
            </para>
          </listitem>
        </itemizedlist>
      </step>
      <step>
        <title>Adjust the cache timeout of the underlying cache region
        <para>
          If you configure your underlying cache implementation to use expiry or timeouts, set the cache timeout of the
          underlying cache region for the <code>UpdateTimestampsCache to a higher value than the timeouts of any
          of the query caches. It is possible, and recommended, to set the UpdateTimestampsCache region never to
          expire. To be specific, a LRU (Least Recently Used) cache expiry policy is never appropriate.
        </para>
      </step>
      <step>
        <title>Enable results caching for specific queries
        <para>
          Since most queries do not benefit from caching of their results, you need to enable caching for individual
          queries, e ven after enabling query caching overall. To enable results caching for a particular query, call
          <methodname>org.hibernate.Query.setCacheable(true). This call allows the query to look for
          existing cache results or add its results to the cache when it is executed.
        </para>
      </step>
    </procedure>
    <para>
      The query cache does not cache the state of the actual entities in the cache. It caches identifier values and
      results of value type. Therefore, always use the query cache in conjunction with the second-level
      cache for those entities which should be cached as part of a query result cache.
    </para>
    
    <section>
      <title>Query cache regions
      <para>
        For fine-grained control over query cache expiration policies, specify a named cache region for a particular
        query by calling <methodname>Query.setCacheRegion().
      </para>

      <example>
        <title>Method setCacheRegion
        <programlisting language="Java" role="JAVA">
      </example>

      <para>
        To force the query cache to refresh one of its regions and disregard any cached results in the region, call
        <code>org.hibernate.Query.setCacheMode(CacheMode.REFRESH). In conjunction with the region defined for the
        given query, Hibernate selectively refreshes the results cached in that particular region. This is much more
        efficient than bulk eviction of the region via <code>org.hibernate.SessionFactory.evictQueries().
      </para>
      
    </section>

  </section>
  
  <section>
    <title>Second-level cache providers
    <para>
      Hibernate is compatible with several second-level cache providers. None of the providers support all of
      Hibernate's possible caching strategies. <xref linkend="caching-provider-table" /> lists the providers, along with
      their interfaces and supported caching strategies. For definitions of caching strategies, see <xref
      linkend="caching-strategies-list" />.
    </para>
    
    <section>
      <title>Configuring your cache providers
      <para>
        You can configure your cache providers using either annotations or mapping files.
      </para>
      <formalpara>
        <title>Entities
        <para>
          By default, entities are not part of the second-level cache, and their use is not recommended. If you
          absolutely must use entities, set the <code>shared-cache-mode element in
          <filename>persistence.xml, or use property javax.persistence.sharedCache.mode
          in your configuration. Use one of the values in <xref linkend="shared-cache-mode-values" />.
        </para>
      </formalpara>
      <table id="shared-cache-mode-values">
        <title>Possible values for Shared Cache Mode
        <tgroup cols="2">
          <thead>
            <row>
              <entry>Value
              <entry>Description
            </row>
          </thead>
          <tbody>
            <row>
              <entry>ENABLE_SELECTIVE
              <entry>
                <para>
                  Entities are not cached unless you explicitly mark them as cachable. This is the default and
                  recommended value.
                </para>
              </entry>
            </row>
            <row>
              <entry>DISABLE_SELECTIVE
              <entry>
                <para>
                  Entities are cached unless you explicitly mark them as not cacheable.
                </para>
              </entry>
            </row>
            <row>
              <entry>ALL
              <entry>
                <para>
                  All entities are always cached even if you mark them as not cacheable.
                </para>
              </entry>
            </row>
            <row>
              <entry>NONE
              <entry>
                <para>
                  No entities are cached even if you mark them as cacheable. This option basically disables second-level
                  caching.
                </para>
              </entry>
            </row>
          </tbody>
        </tgroup>
      </table>
      <para>
        Set the global default cache concurrency strategy The cache concurrency strategy with the
        <property>hibernate.cache.default_cache_concurrency_strategy configuration property. See  annotation.
        </para>
      </note>
      <example id="configuring-cache-providers-annotations">
        <title>Configuring cache providers using annotations
        <programlisting language="Java" role="JAVA">
        <para>
          You can cache the content of a collection or the identifiers, if the collection contains other entities. Use
          the <code>@Cache annotation on the Collection property.
        </para>
        <para>
          <code>@Cache can take several attributes.
        </para>
        <variablelist>
          <title>Attributes of @Cache annotation
          <varlistentry>
            <term>usage
            <listitem>
              <para>
                The given cache concurrency strategy, which may be:
              </para>
              <itemizedlist>
                <listitem>
                  <para>
                    <literal>NONE
                  </para>
                </listitem>
                <listitem>
                  <para>
                    <literal>READ_ONLY
                  </para>
                </listitem>
                <listitem>
                  <para>
                    <literal>NONSTRICT_READ_WRITE
                  </para>
                </listitem>
                <listitem>
                  <para>
                    <literal>READ_WRITE
                  </para>
                </listitem>
                <listitem>
                  <para>
                    <literal>TRANSACTIONAL
                  </para>
                </listitem>
              </itemizedlist>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>region
            <listitem>
              <para>
                The cache region. This attribute is optional, and defaults to the fully-qualified class name of the
                class, or the qually-qualified role name of the collection.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>include
            <listitem>
              <para>
                Whether or not to include all properties.. Optional, and can take one of two possible values.
              </para>
              <itemizedlist>
                <listitem>
                  <para>
                    A value of <literal>all includes all properties. This is the default.
                  </para>
                </listitem>
                <listitem>
                  <para>
                    A value of <literal>non-lazy only includes non-lazy properties.
                  </para>
                </listitem>
              </itemizedlist>
            </listitem>
          </varlistentry>
        </variablelist>
      </example>

      <example>
        <title>Configuring cache providers using mapping files
        <programlisting language="XML" role="XML">
        <para>
          Just as in the <xref linkend="configuring-cache-providers-annotations" />, you can provide attributes in the
          mapping file. There are some specific differences in the syntax for the attributes in a mapping file.
        </para>
        <variablelist>
          <varlistentry>
            <term>usage
            <listitem>
              <para>
                The caching strategy. This attribute is required, and can be any of the following values.
              </para>
              <itemizedlist>
                <listitem>transactional
                <listitem>read-write
                <listitem>nonstrict-read-write
                <listitem>read-only
              </itemizedlist>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>region
            <listitem>
              <para>
                The name of the second-level cache region. This optional attribute defaults to the class or collection
                role name.
              </para>
            </listitem>
          </varlistentry>
          <varlistentry>
            <term>include
            <listitem>
              <para>
                Whether properties of the entity mapped with <literal>lazy=true can be cached when
                attribute-level lazy fetching is enabled. Defaults to <literal>all and can also be
                <literal>non-lazy.
              </para>
            </listitem>
          </varlistentry>
        </variablelist>
        <para>
          Instead of <code><cache>, you can use <class-cache> and
          <code><collection-cache> elements in hibernate.cfg.xml.
        </para>
      </example>
    </section>
    <section id="caching-strategies-list">
      <title>Caching strategies
      <variablelist>
        <varlistentry>
          <term>read-only
          <listitem>
            <para>
              A read-only cache is good for data that needs to be read often but not modified. It is simple, performs
              well, and is safe to use in a clustered environment.
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>nonstrict read-write
          <listitem>
            <para>
              Some applications only rarely need to modify data. This is the case if two transactions are unlikely to
              try to update the same item simultaneously. In this case, you do not need strict transaction isolation,
              and a nonstrict-read-write cache might be appropriate. If the cache is used in a JTA environment, you must
              specify <classname>hibernate.transaction.manager_lookup_class. In other environments, ensore
              that the transaction is complete before you call <methodname>Session.close() or
              <methodname>Session.disconnect().
            </para>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>read-write
          <listitem>
            <para>
              A read-write cache is appropriate for an application which needs to update data regularly. Do not use a
              read-write strategy if you need serializable transaction isolation. In a JTA environment, specify a
              strategy for obtaining the JTA TransactionManager by setting the property
              <property>hibernate.transaction.manager_lookup_class. In non-JTA environments, be sure the
              transaction is complete before you call <methodname>Session.close() or
              <methodname>Session.disconnect().
            </para>
            <note>
              <para>
                To use the read-write strategy in a clustered environment, the underlying cache implementation must
                support locking. The build-in cache providers do not support locking.
              </para>
            </note>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>transactional
          <listitem>
            <para>
              The transactional cache strategy provides support for transactional cache providers such as JBoss
              TreeCache. You can only use such a cache in a JTA environment, and you must first specify
              <classname>hibernate.transaction.manager_lookup_class.
            </para>
          </listitem>
        </varlistentry>
      </variablelist>
    </section>
    <section id="caching-provider-table">
      <title>Second-level cache providers for Hibernate
      <informaltable>
        <tgroup cols="5">
          <thead>
            <row>
              <entry>Cache
              <entry>Interface
              <entry>Supported strategies
            </row>
          </thead>
          <tbody>
            <row>
              <entry>HashTable (testing only)
              <entry>
              <entry>
                <itemizedlist>
                  <listitem>read-only
                  <listitem>nontrict read-write
                  <listitem>read-write
                </itemizedlist>
              </entry>
            </row>
            <row>
              <entry>EHCache
              <entry>
              <entry>
                <itemizedlist>
                  <listitem>read-only
                  <listitem>nontrict read-write
                  <listitem>read-write
                </itemizedlist>
              </entry>
            </row>
            <row>
              <entry>OSCache
              <entry>
              <entry>
                <itemizedlist>
                  <listitem>read-only
                  <listitem>nontrict read-write
                  <listitem>read-write
                </itemizedlist>
              </entry>
            </row>
            <row>
              <entry>SwarmCache
              <entry>
              <entry>
                <itemizedlist>
                  <listitem>read-only
                  <listitem>nontrict read-write
                </itemizedlist>
              </entry>
            </row>
            <row>
              <entry>JBoss Cache 1.x
              <entry>
              <entry>
                <itemizedlist>
                  <listitem>read-only
                  <listitem>transactional
                </itemizedlist>
              </entry>
            </row>
            <row>
              <entry>JBoss Cache 2.x
              <entry>
              <entry>
                <itemizedlist>
                  <listitem>read-only
                  <listitem>transactional
                </itemizedlist>
              </entry>
            </row>
          </tbody>
        </tgroup>
      </informaltable>
    </section>
  </section>

  <section>
    <title>Managing the cache
    
    <section>
      <title>Moving items into and out of the cache
      <variablelist>
        <title>Actions that add an item to internal cache of the Session
        <varlistentry>
          <term>Saving or updating an item
          <listitem>
            <itemizedlist>
              <listitem>
                <para>
                  <methodname>save()
                </para>
              </listitem>
              <listitem>
                <para>
                  <methodname>update()
                </para>
              </listitem>
              <listitem>
                <para>
                  <methodname>saveOrUpdate()
                </para>
              </listitem>
            </itemizedlist>
          </listitem>
        </varlistentry>
        <varlistentry>
          <term>Retrieving an item
          <listitem>
            <itemizedlist>
              <listitem>
                <para>
                  <methodname>load()
                </para>
              </listitem>
              <listitem>
                <para>
                  <methodname>get()
                </para>
              </listitem>
              <listitem>
                <para>
                  <methodname>list()
                </para>
              </listitem>
              <listitem>
                <para>
                  <methodname>iterate()
                </para>
              </listitem>
              <listitem>
                <para>
                  <methodname>scroll()
                </para>
              </listitem>
            </itemizedlist>
          </listitem>
        </varlistentry>
      </variablelist>
      <formalpara>
        <title>Syncing or removing a cached item
        <para>
          The state of an object is synchronized with the database when you call method
          <methodname>flush(). To avoid this synchronization, you can remove the object and all collections
          from the first-level cache with the <methodname>evict() method. To remove all items from the
          Session cache, use method <methodname>Session.clear().
        </para>
      </formalpara>
      <example>
        <title>Evicting an item from the first-level cache
        <programlisting language="Java" role="JAVA">
      </example>
      <formalpara>
        <title>Determining whether an item belongs to the Session cache
        <para>
          The Session provides a <methodname>contains() method to determine if an instance belongs to the
          session cache.
        </para>
      </formalpara>
      
      <example>
        <title>Second-level cache eviction
        <para>
          You can evict the cached state of an instance, entire class, collection instance or entire collection role,
          using methods of <classname>SessionFactory.
        </para>
        <programlisting language="Java" role="JAVA">
      </example>       
      <section>
        <title>Interactions between a Session and the second-level cache
        <para>
          The CacheMode controls how a particular session interacts with the second-level cache.
        </para>
        <informaltable>
          <tgroup cols="2">
            <tbody>
              <row>
                <entry>CacheMode.NORMAL
                <entry>reads items from and writes them to the second-level cache.
              </row>
              <row>
                <entry>CacheMode.GET
                <entry>reads items from the second-level cache, but does not write to the second-level cache except to
                update data.</entry>
              </row>
              <row>
                <entry>CacheMode.PUT
                <entry>writes items to the second-level cache. It does not read from the second-level cache. It bypasses
                the effect of <property>hibernate.cache.use_minimal_puts and forces a refresh of the
                second-level cache for all items read from the database.</entry>
              </row>
            </tbody>
          </tgroup>
        </informaltable>
      </section>
      
      <section>
        <title>Browsing the contents of a second-level or query cache region
        <para>
          After enabling statistics, you can browse the contents of a second-level cache or query cache region.
        </para>
        <procedure>
          <title>Enabling Statistics
          <step>
            <para>
              Set <code>hibernate.generate_statistics to true.
            </para>
          </step>
          <step>
            <para>
              Optionally, set <code>hibernate.cache.use_structured_entries to true, to cause
              Hibernate to store the cache entries in a human-readable format.
            </para>
          </step>
        </procedure>
        <example>
          <title>Browsing the second-level cache entries via the Statistics API 
        </example>
      </section>
    </section>
  </section>
</chapter>

Other Hibernate examples (source code examples)

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