Meena Rajani
Meena Rajani

Reputation: 153

Query Cache Hibernate loading entities

Can any one help me resolving this question. I am using Infinispan as second level cache and Hibernate as ORM. I have turned on both enityt and query cache.

I have two queries, for example Q1 is "selet b from BokkEntity b where b.id < 5" and another like Q2 is "select b from BokkEntity b where b.id < 7"
The first time I am running Q1 it loads 5 objects from persistent store into cache. running second query first time loads 7 objects in Cache. While first five objects are common in both query. And according to my understanding query Cache always just stores id and then if entity cache is on the search is done inside the cache for the objects, referenced by ids, in query cache.

So my Question is why both Q2 is loading all the objects again and overwriting these in entity cache while I run Q2(after running q1) first time.

I have checked query cache is working properly for any subsequent request. ie, if I rerun Q1 or Q2 the data is accessed from cache.

This is urgent, I will appreciate the effort.

Thanks

Meena

Upvotes: 4

Views: 517

Answers (1)

Shadow Man
Shadow Man

Reputation: 3402

Hibernate has no way of telling which results of a query it already has unless it has run that exact same query before. Thus this is the expected behavior.

Per the Hibernate documentation:

If you have queries that run over and over, with the same parameters, query caching provides performance gains.

Note the phrase: with the same parameters.

If you are asking hibernate to retrieve an entity by id it can easily search its cache. But with a query that it hasn't run before, any number of things may have been inserted since the last run (it only invalidates across servers, it does not add or update remote server caches).

Also, with queries, hibernate is overeager (a good thing) about invalidating its query caches (any time a database update occurs you will likely lose all cached query results).

The kind of logic that they would have to implement to ensure that your 2 queries could be merged and split would be extremely complicated and likely would not be possible without an intimate knowledge of your database structure and program logic.

Upvotes: 1

Related Questions