Step 5- Caching in hibernate


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.
    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.
    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)

     Add cache usage in hbm file, for which you want to use second level cache
    <class name=”ClassName” table=”tableName”>
    <cache usage=”read-only” />

    write-only, read-write only, restricted read-write only, read-only is widely used and famous.
    Add these 3 lines in cfg file,
    <property name=”cache.provider_class”> org.hibernate.cache.EhCacheProvider
    <property name=”hibernate.cache.use_second_level_cache”>true</property>


    <property name=”hibernate.cache.region.factory_class”> org.hibernate.cache.ehcache.EhCacheRegionFactory

    step3- Add 2 jars for hibernate second level cache. 
    similar to hibernate-core version.
    latest version.

Extra-Query Level cache in hibernate-

  • Query Cache is used to cache the results of a query.
    Session session3=factory.openSession();
    Query query=session3.createQuery(“from Employee e where”); //query will execute
    Employee em=(Employee)query.getSingleResult();

    Query query1=session3.createQuery(“from Employee e where”); //will come from query cache, query will not run
    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>