I have and existing query like
Now when i am running the above query in a loop for 10 times, it always hits the database and gets the result, the cache logs says "item already cached" also the SecondLevelCacheStatistics show 0 hits.
Now when i added the setCacheable(true) to the below query
The above worked and i got the expected result
My question is that as i am working on existing maintaince project, do i need to add setCacheable(true) to every concerned query.
Does second level caache depends on query cache (hibernate.cache.use_query_cache) ' value.
I there any other way out so that i need not to write setCacheable(true) to every query?
So yes, you need to define every query you want to be cacheable as such explicitly. Its worth noting that when it comes to performance changes to a Hibernate application, the query cache is the last performance change you would normally look at. If you've tried everything else and the application is still not performing well then you could look at the query cache, assuming your application's business logic is OK with out of date results. If you have not performance tested your application and are adding the query cache on a hunch, stop what you are doing. Typically there are far easier way to improve the performance of a Hibernate application.
Paul Sturrock wrote:A cached query is a different thing from cached entities. Remember, queries do not necessarily load entities (i.e. select property1 from entity will just get that property). When you cache a query what you cache are the ids of entities that match the criteria when the query was run.
My understanding on your point is like
A query wil hit the database every time it got fired but if the query is cacheble the DB hit is saved for the second and subsequent times .
the query cache makes the query cachable but the secong level cache makes the Entities catchable based on their identifier(pk)
The second level cache is only used when accessing the object by Primary Key, means the searching for whole entities based on Primary Key
ie with session.get(), session.load() methods.
Please correct me if i am wrong.