Cache definition-
Cache is a temporary data which is used to speed up the performance.
Types of caching in hibernate-
1-Session Cache/First level cache in hibernate-
- First level cache is enabled by default.
- First level cache can’t be disabled.
- Objects are retrieved from current session.
Example-
i.e. for session object (s1) and Employee class.
Session s1=sessionfactory.openSession();
Employee emp1=(Employee)s1.load(Employee.class,1); // query will execute and data will be saved into first level cache
Employee emp2=(Employee)s1.load(Employee.class,1); // query will not execute, and data will be fetched from first level cache
2- SessionFactory Cache/Second level cache in hibernate-
- Second level cache is disabled by default.
- Second level cache is configured to use.
- Objects can be retrieved from various sessions.
Example-
Session s1=sessionfactory.openSession();
Employee emp1=(Employee)s1.load(Employee.class,1); //query will execute and data will be saved into first level(by default) and into Second level cache as well(only if configured)
Session s2=sessionfactory.openSession();
Employee emp2=(Employee)s2.load(Employee.class,1); //query will not execute and data will be fetched from second level cache.Note- Data can’t be fetched from first level cache here because different session has been created, and first level cache only works with same session. - Steps to enable Second level cache-(we are choosing “ehCache” vendor, because it is widely used)
Step1- Add cache usage in hbm file, for which you want to use second level cache
i.e.<hibernate-mapping>
<class name=”ClassName” table=”tableName”>
<cache usage=”read-only” />
i.e.- write-only, read-write only, restricted read-write only, read-only is widely used and famous.
Step2- Add these 3 lines in cfg file,
i.e.
<property name=”cache.provider_class”> org.hibernate.cache.EhCacheProvider
</property><property name=”hibernate.cache.use_second_level_cache”>true</property><property name=”hibernate.cache.region.factory_class”> org.hibernate.cache.ehcache.EhCacheRegionFactory
</property>step3- Add 2 jars for hibernate second level cache.
hibernate-ehCache-x.x.x.jar, similar to hibernate-core version.
ehCache-x.x.jar, latest version.
Extra-Query Level cache in hibernate-
- Query Cache is used to cache the results of a query.
i.e.
Session session3=factory.openSession();
Query query=session3.createQuery(“from Employee e where e.id=1”); //query will execute
query.setCacheable(true);
Employee em=(Employee)query.getSingleResult();
Query query1=session3.createQuery(“from Employee e where e.id=1”); //will come from query cache, query will not run
query1.setCacheable(true);
Employee em1=(Employee)query1.getSingleResult(); - Stepes to enable query level cache-
step 1- Only add this line to cfg file.
i.e. <property name=”hibernate.cache.use_query_cache”>true</property>
Done!!