Your next step after considering the concurrency strategies you will use for your cache candidate classes is to pick a cache provider. Hibernate forces you to choose a single cache provider for the whole application.
Every cache provider is not compatible with every concurrency strategy. The following compatibility matrix will help you choose an appropriate combination.
You will specify a cache provider in hibernate.cfg.xml configuration file. We choose EHCache as our second-level cache provider:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <propertyname="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </property> <propertyname="hibernate.connection.driver_class"> com.mysql.jdbc.Driver </property> <!-- Assume students is the database name --> <propertyname="hibernate.connection.url"> jdbc:mysql://localhost/test </property> <propertyname="hibernate.connection.username"> root </property> <propertyname="hibernate.connection.password"> root123 </property> <propertyname="hibernate.cache.provider_class"> org.hibernate.cache.EhCacheProvider </property> <!-- List of XML mapping files --> <mappingresource="Employee.hbm.xml"/> </session-factory> </hibernate-configuration> Now, you need to specify the properties of the cache regions. EHCache has its own configuration file, ehcache.xml, which should be in the CLASSPATH of the application. A cache configuration in ehcache.xml for the Employee class may look like this:
<diskStorepath="java.io.tmpdir"/>
<defaultCache maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" /> eternal="true" timeToIdleSeconds="0" timeToLiveSeconds="0" overflowToDisk="false" /> That's it, now we have second-level caching enabled for the Employee class and Hibernate now hits the second-level cache whenever you navigate to a Employee or when you load a Employee by identifier. You should analyze your all the classes and choose appropriate caching strategy for each of the classes. Sometime, second-level caching may downgrade the performance of the application. So it is recommended to benchmark your application first without enabling caching and later on enable your well suited caching and check the performance. If caching is not improving system performance then there is no point in enabling any type of caching. |