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.
Hibernate Second Level Cache ExampleTo understand the second level cache through example, we need to follow the following steps:
Here, we are assuming, there is emp1012 table in the oracle database containing some records.1) Create the persistent class using Maven.File: Employee.java 2) Add project information and configuration in pom.xml file.Open pom.xml file and click source. Now, add the below dependencies between <dependencies>....</dependencies> tag. 3) Create the Configuration fileFile: hibernate.cfg.xml To implement second level cache, we need to define cache.provider_class property in the configuration file. 4) Create the class that retrieves the persistent object.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 |