Hibernate Second Level Cache
Hibernate second level cache uses a common cache for all the session object of a session factory. It is useful if you have multiple session objects from a session factory.
SessionFactory holds the second level cache data. It is global for all the session objects and not enabled by default.
Different vendors have provided the implementation of Second Level Cache.
Each implementation provides different cache usage functionality. There are four ways to use second level cache.
The cache-usage property can be applied to class or collection level in hbm.xml file. The example to define cache usage is given below:
Let's see the second level cache implementation and cache usage.
3 extra steps for second level cache example using EH cache
1) Add 2 configuration setting in hibernate.cfg.xml file
2) Add cache usage setting in hbm file
3) Create ehcache.xml file
Hibernate Second Level Cache Example
To understand the second level cache through example, we need to create following pages:
Here, we are assuming, there is emp1012 table in the oracle database containing some records.
Here, we are using read-only cache usage for the class. The cache usage can also be used in collection.
To implement second level cache, we need to define cache.provider_class property in the configuration file.
You need to create ehcache.xml file to define the cache property.
defaultCache will be used for all the persistent classes. We can also define persistent class explicitely by using the cache element.
eternal If we specify eternal="true", we don't need to define timeToIdleSeconds and timeToLiveSeconds attributes because it will be handled by hibernate internally. Specifying eternal="false" gives control to the programmer, but we need to define timeToIdleSeconds and timeToLiveSeconds attributes.
timeToIdleSeconds It defines that how many seconds object can be idle in the second level cache.
timeToLiveSeconds It defines that how many seconds object can be stored in the second level cache whether it is idle or not.
As we can see here, hibernate does not fire query twice. If you don't use second level cache, hibernate will fire query twice because both query uses different session objects.