I am using Hibernate 3.2.5 for my application. I am trying to implement Query Cache but it is not working.
Problem Description:
For the first time, the DB is hit, data is fetched and cached. For the second time, for the same query again the DB is hit rather than taking the data from the cache. For the second time, I want it to take it from the cache rather than hitting the DB again.
For enabling the Query Cache, I made the below entries in the cfg.xml file:
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
Created the file: ehcache.xml and added the below entry in the hbm.xml files:
<cache usage="read-only" />
Below is the code I tried:
SessionFactory sf = new Configuration().configure("trial.cfg.xml").buildSessionFactory();
Session session = sf.openSession();
List departments1 = session.createQuery("from Dept dept where dept.deptId = 1")
.setCacheable(true)
.setCacheRegion("departmentId")
.list();
//Some business operations
session.flush();
session.close();
//Some business operations
Session session1 = sf.openSession();
List departments2 = session1.createQuery("from Dept dept where dept.deptId = 1").list();
//In the above line again it is hitting the DB rather than taking it from the cache.
I believe that I am missing something for which it is not fetching the data from the cache and hence hitting the DB. Kindly let me know how to make this Query Cache work.