Monday, 18 April 2016

How to configure Ehcache at Entity level in Spring+Hibernate+JPA application

Add the below entries in ehcache.xml which is placed in resources folder incase of maven project and otherwise in the classpath



<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd"
         updateCheck="false" monitoring="autodetect"
         dynamicConfig="true">
<defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="1200" timeToLiveSeconds="1200"     overflowToDisk="true" diskPersistent="false"
     diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"/>
   
     <cache name="org.hibernate.cache.internal.StandardQueryCache"  maxElementsInMemory="10000"   eternal="false"   timeToIdleSeconds="3600"  timeToLiveSeconds="3600"/>
  <cache name="org.hibernate.cache.spi.UpdateTimestampsCache"  maxElementsInMemory="10000"  eternal="true"/>  
     <cache name="com.traveldesk.TravelDetail"  eternal="true"  maxElementsInMemory="10000"/>  
</ehcache>


The annotation @cache  helps in making the entity as a cacheable one

@Entity
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
@Table(name="TRAVEL_DETAIL" , schema="travel")
@NamedQuery(name="TravelDetail.findAll", query="SELECT d FROM TravelDetail d")
public class TravelDetail implements Serializable { }


The properties that are to be provided in the persistence.xml are as follows


<property name="hibernate.cache.region_prefix" value=""/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.EhCacheProvider" />
            <property name="hibernate.cache.use_second_level_cache" value="true" />
            <property name="hibernate.cache.use_query_cache" value="true" />
            <property name="hibernate.generate_statistics" value="true" />
            <property name="hibernate.cache.use_structured_entries" value="true" />                
            <property name="net.sf.ehcache.configurationResourceName" value="META-INF/ehcache.xml" />
<property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory" />



No comments:

Post a Comment