R – How to enable hibernate query cache on a session level only

hibernatemultithreadingquery-cachesessionsession-cache

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

Best Answer

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");