Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable hibernate query cache on a session level only?

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

like image 380
Franz See Avatar asked Sep 16 '09 12:09

Franz See


People also ask

How do I enable query cache in Hibernate?

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.

What is session level cache in Hibernate?

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.

Which Hibernate cache is used on process level or cluster level?

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.


2 Answers

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");
like image 173
ChssPly76 Avatar answered Sep 24 '22 21:09

ChssPly76


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.

like image 33
skaffman Avatar answered Sep 21 '22 21:09

skaffman