Five ‘s Weblog

November 11, 2007

The process-level cache in Hibernate

Filed under: ORM — by powerdream5 @ 8:03 pm
Tags: , ,

11_11_1_2007.jpg

        Hibernate has two kinds of cache, which are the first-level cache and the second-level cache. We also call the first-leve cache session cache, and the second-level cache process-level cache. The first-level cache is mandatory and can’t be turned off; However, the second-level cache in Hibernate is optional. Because the process-level cache caches objects across sessions and has process or cluster scope, in some situation, turning on the process-level cache can improve the performance of the application. In fact, before accessing the database to load an object, Hibernate will first look in the Session cache and then in the process-level cache.

       The process-level cache is best used to store objects that change relatively infrequently, and it is set up in two steps. First, you have to decide which concurrency strategy to use. After that, you configure cache expiration and physical cache attribtes using the cache provider. Hibernate supports a variety of caching strategies including:
read-only : which is suitable for objects which never changes. Use if for reference data only.
read-write : which is suitable for objects that are modified by the application.

      To cache these classes in the process-level cache, we must use the <cache> element in the O/R mapping. For example:
<class name=”?” talbe=”?”>
      <cache usage=”read-wirte” />
      …
</class>

      The usage=”read-write” attribute specifies that instances of this class are sometimes updated by the application. One thing needed to remember is that you must enable lazy loading for relationships that are from objects that not cached to objects that are cached to ensure that the applications uses the cache.
<class name=”?” talbe=”?”>
      <cache usage=”read-wirte” />
       …

       <set name=”?” lazy=”true”>
                /*collections require their own <cache> element*/
               <cache usage=”read-only” />
                …
        </set>
</class>

11_11_2_2007.jpg

Create a free website or blog at WordPress.com.