91-9990449935 0120-4256464 |
Hibernate Second Level CacheHibernate 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 cache1) 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 ExampleTo 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.File: Employee.java
File: employee.hbm.xml
Here, we are using read-only cache usage for the class. The cache usage can also be used in collection. File: hibernate.cfg.xml
To implement second level cache, we need to define cache.provider_class property in the configuration file. File: ehcache.xml
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. File: FetchTest.java
Output: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.
Next TopicHibernate And Struts Integration
|