Related to this question
Premise:
These are my assumptions, based on my reading, experience and understanding, they may be wrong, if they are, please comment and I'll edit the question.
- Query cache is good mostly along with 2nd level cache
- Query cache caches the identifiers results of queries + parameters
- Query cache is risky if the database was changed, and it wasn't reflected to the cache
Question:
I have an object that is not in the 2nd level cache. Due to some bad programming or other constraints, the code that loads the object is being called several time in the same hibernate session. The retrival is using an HQL find query e.g.
hibernateTemplate.find("from Foo f where f.bar > ?", bar);
Before adding query cache, if the above code was called N times within the same Hibernate Session, there were N hits to the database
Then I wanted to see what happens if I add query cache:
Query query = session.createQuery("from Foo f where f.bar > ?");
query.setCacheable(true);
query.setParameter(bar);
query.list();
When I added query cache, i've noticed that during the same session, hibernate doesn't hit the database N times anymore, only once per session.
- So my first assumption is that Hibernate first searches in the Session Cache, then in the 2nd Level Cache. Is this assumption correct?
- I also assume that if the object (
Foo
) which is not in the 2nd level cache, was changed in the database, then query cache, being cross session scoped, will return the wrong identifiers, and thus the wrong objects. Is that correct? - Is it then safe to say that using query cache for queries that include immutable information even for non 2L cached objects, is a good practice? (e.g. a query that its where clause contains a condition that will always return the same results, e.g. "select p.ser_num where p.id = ?" when ser_num and id couples do not change once created)
By the way, in the related question it is claimed that query cache doesn't work on the Session Cache scope. Am I missunderstanding that claim, or anything else?