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 session1, Employee persist class.
    Session session1=sessionfactory.openSession();
    Employee emp1=(Employee)session1.load(Employee.class,1); //execute query
    Employee emp2=(Employee)session1.load(Employee.class,1); // will come from first level cache, query will not execute

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 session1=sessionfactory.openSession();
    Employee emp1=(Employee)session1.load(Employee.class,1); //execute query
    Session session2=sessionfactory.openSession();
    Employee emp2=(Employee)session2.load(Employee.class,1); //will come from second level cache, if manually enabled only.
  • Stepes 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
    <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,
    <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. 
    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 e.id=1”); //query will execute
    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
    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>