Search code examples
hibernatecachingehcachesecond-level-cachequery-cache

Cache all queries by default using hibernate/ehcache?


Our application handles read-only data, so we are considering using Hibernate query cache features (implemented by ehcache) on all queries.

So far we enabled both second level and query caches:

<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>

And then told hibernate that each query was cacheable:

query.setHint("org.hibernate.cacheable", true);

I can identify two drawbacks from this approach:

  • code redudancy (as you have to manually add the hint for each query)

  • hibernate dependency (so far the code is clean from direct
    hibernate references, using only JPA annotations)

Is there any way to achieve this, i.e. caching all queries, using only configuration files?

Thank you!


Solution

  • No, there is not, because that would not make much sense (or better said, it would not be useful in 99.99% of the use cases).

    There is always a different entry in the cache for each combination of the query and the input parameters (bind variables).

    The query cache should be enabled for queries which select from entities (tables) that are changed (inserted into, updated, deleted from) rarely and for which there will not be a large number of combinations of different input parameters.