0

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.

3
  • What make you say that it's hitting the database? If you are just relying on the select statement printed in log file then this is not the right observation. Commented Jun 30, 2013 at 11:48
  • Yes I was relying on the select statement printed in the log file for checking whether it's a DB hit or not. Kindly let me know what is the other way/proper way to check if it's a DB or not? Commented Jun 30, 2013 at 15:14
  • I waited for getting a reply on this...but it seems I have to create a different thread for this :( Commented Jul 2, 2013 at 13:41

1 Answer 1

1

The second query is not cacheable, so it doesn't use the cache. As simple as that.

Note that if this is your real code, you should simple use session.get(Dept.class, 1) to get the department.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.