简体   繁体   中英

Is it possible to manully add values to Hibernate query cache map?

is it possible to manully add keys to the map of Hibernate query cache?

Please see my reasoning below:

I have a query as follows:

from UserTable as u where u.username="Dan" and password="123456"

And the result query returns a user with the id of 3.

The first query is only executes once, and loaded to the query cache.

Now, while the first result is cached, I issue the following query

from UserTable as u where u.id=3

Which will return the same user , but as I learnt from various site, like so , the queries will be treated as different queries entirely by the cache (please correct me if I'm wrong of course).

Is there a way to tell Hibernate that both queries return the same data? Doing so will save hibernate from hitting the database the second time.

A theoretical solution I can think of is, after issuning the first query, inject the second query with the first query value to the cache, but I'm not sure it's possible.

Is there a way to tell Hibernate that both queries return the same data? No.

Doing so will save hibernate from hitting the database the second time. It shouldn't be a big deal. Query caching is meant to be used for queries that are executed often, so one execution more shouldn't make a large difference.

A theoretical solution I can think of is, after issuing the first query, inject the second query with the first query value to the cache, but I'm not sure it's possible. Theoretically it is possible, but it would be very complex to implement manually (cache entry format, timestamp cache, proper synchronization with other concurrent sessions, etc).

The solution to your specific example is to enable second-level caching for UserTable entity, and load the user with session.load(UserTable.class, id) instead of executing the second query. This way the user will be retrieved from the L2 cache because it was loaded into it in the first query.

Important: If you have lots of records of UserTable entity, neither any of your queries nor UserTable entity should be cached. Take a look at this blog for an overview and best practices about L2 caching.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM