|
Answer» EHCache is the BEST choice for UTILIZING hibernate second level cache. Following steps are required to enable EHCache in hibernate application. - Add hibernate-ehcache dependency in your maven project, if it’s not maven then add corresponding jars.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>4.3.5.Final</version>
</dependency> - Add below properties in hibernate configuration file.
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<!-- For singleton factory -->
<!-- <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</property>
-->
<!-- enable second level cache and query cache -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="net.sf.ehcache.configurationResourceName">/myehcache.xml</property> - Create EHCache configuration file, a sample file myehcache.xml would look like below.
<?xml version="1.0" ENCODING="UTF-8"?>
<ehcache xmlns:XSI="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd"updateCheck="true"
monitoring="AUTODETECT"dynamicConfig="true">
<diskStorepath="java.io.tmpdir/ehcache" />
<defaultCachemaxEntriesLocalHeap="10000"eternal="false"
timeToIdleSeconds="120"timeToLiveSeconds="120"diskSpoolBufferSizeMB="30"
maxEntriesLocalDisk="10000000"diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"statistics="true">
<persistence strategy="localTempSwap" />
</defaultCache>
<cache name="employee" maxEntriesLocalHeap="10000"eternal="false"
timeToIdleSeconds="5"timeToLiveSeconds="10">
<persistence strategy="localTempSwap" />
</cache>
<cache name="org.hibernate.cache.internal.StandardQueryCache"
maxEntriesLocalHeap="5"eternal="false"timeToLiveSeconds="120">
<persistence strategy="localTempSwap" />
</cache>
<cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
maxEntriesLocalHeap="5000"eternal="true">
<persistence strategy="localTempSwap" />
</cache>
</ehcache> - Annotate entity beans with @Cache annotation and caching strategy to use. For example,
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
@Entity
@Table(name = "ADDRESS")
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY, region="employee")
public class Address {
} Hibernate will now use the EHCache for second level caching.
|