What if I have a query that gets called multiple times in a single thread, and I just want to cache that query (and its result) for that thread (or for that session since I'm using one session per thread), how can I do that ?
Note: My 2nd level cache is turned on but it's used mostly for session.get(...). But I do not want to use it for my query cache because I only need it to live for the duration of my thread ( / session ).
Thanks
To use the query cache, you must first activate it using the hibernate. cache. use_query_cache="true" property in the configuration file. By setting this property to true, you make Hibernate create the necessary caches in memory to hold the query and identifier sets.
This cache only works at a session level, meaning each session object caches data independently, so there is no sharing of cached data across sessions, and the cached data is deleted when the session closes. This makes the cache only useful for repeated queries in the same session.
The first-level cache is mandatory and can't be turned off; However, the second-level cache in Hibernate is optional. Because the process-level cache caches objects across sessions and has process or cluster scope, in some situation, turning on the process-level cache can improve the performance of the application.
The bottom line here is: you can either manually cache your query results or you can ask Hibernate to do it. While it generally makes little sense to restrict your query cache lifetime to that of session, it can be done using the following approach:
1) Enable query cache
2) Dedicate a specific region for query in question and mark it as cacheable:
Query query = ...;
query.setCacheable(true).setCacheRegion("MY_SPECIAL_QUERY");
3) Evict your query from cache at the end of the session (if you're REALLY sure that's what you want to do):
SessionFactory sessionFactory = ...;
sessionFactory.evictQueries("MY_SPECIAL_QUERY");
Query caching cannot be applied to the session cache. This makes sense, since generally all operations against a session are done by one piece of code, which should just be able to remember the results itself.
You say you don't want to enable 2nd-level query caching, but what would be the harm in doing so? You'd get your desired results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With