I have a collection that does not change (several actually, but in this example a list of TimeZones), which I have placed as immutable, read-only members of the second-level cache using ehcache. Once this Collection is in memory, there should be no reason to go to the database to load it again. That is not what I am seeing, however, and I am wondering if there is a way to modify what I am doing so that the findAll method returns the cached results or if this is simply not supported. I can see the complexities involved with concurrent modifications, but it seems that in the case of an immutable, read-only cache, it *might* be possible to support it.
As an asside, if I do the second test twice and have two instances of the default TimeZone in memory, I am surprised the assertSame(zoneOne, zoneTwo) fails.
Perhaps there is a URL to some additional documentation of ehcache that would help?
Hibernate version:
3.0.3
Mapping documents:
TimeZone is not mutable and the cache is read-only
Code Excerpts:
Code:
public static Collection findAllTimeZones() {
return HibernateUtil.currentSession().createCriteria(TimeZone.class).list();
}
Unit tests:
Code:
public void testCache() throws Exception {
CacheProviderHelper.dumpCacheInfo();
/* first read all TimeZones into memory (and thus into the cache) */
Collection allZones = BankManager.findAllTimeZones();
int initialHitCount = CacheProviderHelper.getHitCount();
HibernateUtil.closeSession();
/* should hit second-level cache */
TimeZone zoneOne = BankManager.getDefaultTimeZone();
int currentHitCount = CacheProviderHelper.getHitCount();
assertEquals(initialHitCount + 1, currentHitCount);
HibernateUtil.closeSession();
initialHitCount = currentHitCount;
allZones = BankManager.findAllTimeZones();
currentHitCount = CacheProviderHelper.getHitCount();
/* I am surprised this isn't a hit. I guess there is no way for the caching machinery to know that the cache is 100% complete. */
//assertEquals(initialHitCount + allZones.size(), currentHitCount);
assertEquals(initialHitCount, currentHitCount);
HibernateUtil.closeSession();
/* here these should all be cache hits. */
for (Iterator i = allZones.iterator(); i.hasNext();) {
HibernateUtil.currentSession().get(TimeZone.class, ((TimeZone)i.next()).getTimeZoneId());
}
currentHitCount = CacheProviderHelper.getHitCount();
assertEquals(initialHitCount + allZones.size(), currentHitCount);
HibernateUtil.closeSession();
}