Setting Up a Read-Only Cache
To begin with something simple, here's the Hibernate mapping for the Country class:

<hibernate-mapping package="com.wakaleo.articles.caching.businessobjects">
<class name="Country" table="COUNTRY" dynamic-update="true">
<meta attribute="implement-equals">true</meta>
<cache usage="read-only"/>
<id name="id" type="long" unsaved-value="null" >
<column name="cn_id" not-null="true"/>
<generator class="increment"/>
</id>
<property column="cn_code" name="code" type="string"/>
<property column="cn_name" name="name" type="string"/>
<set name="airports">
<key column="cn_id"/>
<one-to-many class="Airport"/>
</set>
</class>
</hibernate-mapping>

Suppose you need to display a list of all countries. You could implement this with a simple method in the CountryDAO class as follows:


public class CountryDAO {
...
public List getCountries() {
return SessionManager.currentSession()
.createQuery(
"from Country as c order by c.name")
.list();
}
}

Because this method is likely to be called often, you need to see how it behaves under pressure. So write a simple unit test that simulates five successive calls:


public void testGetCountries() {
CountryDAO dao = new CountryDAO();
for(int i = 1; i <= 5; i++) {
Transaction tx = SessionManager.getSession().beginTransaction();
TestTimer timer = new TestTimer("testGetCountries");
List countries = dao.getCountries();
tx.commit();
SessionManager.closeSession();
timer.done();
assertNotNull(countries);
assertEquals(countries.size(),229);
}
}

You can run this test from either your preferred IDE or the command line using Maven 2 (the demo application provides the Maven 2 project files). The demo application was tested using a local MySQL database. When you run this test, you should get something like the following:


$mvn test -Dtest=CountryDAOTest
...
testGetCountries: 521 ms.
testGetCountries: 357 ms.
testGetCountries: 249 ms.
testGetCountries: 257 ms.
testGetCountries: 355 ms.
[surefire] Running com.wakaleo.articles.caching.dao.CountryDAOTest
[surefire] Tests run: 1, Failures: 0, Errors: 0, Time elapsed: 3,504 sec

So each call takes roughly a quarter of a second, which is a bit sluggish by most standards. The list of countries probably doesn't change very often, so this class would be a good candidate for a read-only cache. So add one.

You can activate second-level caching classes in one of the two following ways:

  1. You activate it on a class-by-class basis in the *.hbm.xml file, using the cache attribute:
    
        <hibernate-mapping package="com.wakaleo.articles.caching.businessobjects">
        <class name="Country" table="COUNTRY" dynamic-update="true">
        <meta attribute="implement-equals">true</meta>
        <cache usage="read-only"/>
        ...
        </class>
        </hibernate-mapping>
        
  2. You can store all cache information in the hibernate.cfg.xml file, using the class-cache attribute:
    
        <hibernate-configuration>
        <session-factory>
        ...
        <property name="hibernate.cache.provider_class">
        org.hibernate.cache.EHCacheProvider
        </property>
        ...
        <class-cache
        class="com.wakaleo.articles.caching.businessobjects.Country"
        usage="read-only"
        />
        </session-factory>
        </hibernate-configuration>
        

Next, you need to configure the cache rules for this class. These rules determine the nitty-gritty details of how the cache will behave. The examples in this demo use EHCache, but remember that each cache implementation is different.

EHCache needs a configuration file (generally called ehcache.xml) at the classpath root. The EHCache configuration file is well documented on the project Web site. Basically, you define rules for each class you want to store, as well as a defaultCache entry for use when you don't explicitly give any rules for a class.

For the first example, you can use the following simple EHCache configuration file:


<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
/>
<cache name="com.wakaleo.articles.caching.businessobjects.Country"
maxElementsInMemory="300"
eternal="true"
overflowToDisk="false"
/>
</ehcache>

This file basically sets up a memory-based cache for Countries with at most 300 elements (the country list contains 229 countries). Note that the cache never expires (the 'eternal=true' property).

Now, rerun the tests to see how the cache performs:


$mvn test -Dtest=CompanyDAOTest
...
testGetCountries: 412 ms.
testGetCountries: 98 ms.
testGetCountries: 92 ms.
testGetCountries: 82 ms.
testGetCountries: 93 ms.
[surefire] Running com.wakaleo.articles.caching.dao.CountryDAOTest
[surefire] Tests run: 1, Failures: 0, Errors: 0, Time elapsed: 2,823 sec

As you would expect, the first query is unchanged since the first time around you have to actually load the data. However, all subsequent queries are several times faster.