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