Spring hibernate ehcache setup
- by Johan Sjöberg
I have some problems getting the hibernate second level cache to work for caching domain objects. According to the ehcache documentation it shouldn't be too complicated to add caching to my existing working application.
I have the following setup (only relevant snippets are outlined):
@Entity
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE
public void Entity {
// ...
}
ehcache-entity.xml
<cache name="com.company.Entity" eternal="false"
maxElementsInMemory="10000" overflowToDisk="true" diskPersistent="false"
timeToIdleSeconds="0" timeToLiveSeconds="300"
memoryStoreEvictionPolicy="LRU" />
ApplicationContext.xml
<bean class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="ds" />
<property name="annotatedClasses">
<list>
<value>com.company.Entity</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.generate_statistics">true</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="net.sf.ehcache.configurationResourceName">/ehcache-entity.xml</prop>
<prop key="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory</prop>
....
</property>
</bean>
Maven dependencies
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.4.0.GA</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-hibernate3</artifactId>
<version>2.0.8</version>
<exclusions>
<exclusion>
<artifactId>hibernate</artifactId>
<groupId>org.hibernate</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.3.2</version>
</dependency>
A test class is used which enables cache statistics:
Cache cache = cacheManager.getCache("com.company.Entity");
cache.setStatisticsAccuracy(Statistics.STATISTICS_ACCURACY_GUARANTEED);
cache.setStatisticsEnabled(true);
// store, read etc ...
cache.getStatistics().getMemoryStoreObjectCount(); // returns 0
No operation seems to trigger any cache changes. What am I missing? Currently I'm using HibernateTemplate in the DAO, perhaps that has some impact.
[EDIT]
The only ehcache log output when set to DEBUG is:
SettingsFactory: Cache region factory : net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory