I am working on implementing caching of certain static data.
I have two approaches :
Which of these approaches works best ? What are the things I must consider ?
If all things equals consider prefering the Spring caching of method call results, the reason being that it's simpler to reason about caching at the level of the service layer.
The Hibernate second level cache works fine but it is in my opinion harder to reason about and it has more pitfalls. For example it does NOT work for queries, only for find by Ids or the loading of lazy associations.
Actually the loading of lazy associations is OFF by default, and needs to be enabled with a hibernate specific annotation at the collection level.
To query the results of queries, you need to use the query cache too, which only caches Id's and queries that return primitive values only. The Ids of the cached query are then resolved against the second level cache.
In both cases and with caches in general, the problem is usually to find the right moment to invalidate the cache. Both ways allows to configure expiration and max number of elements/memory at the level of the cache provider such as ehcache.
For clearing the cache explicitly, Spring provides @CacheEvict
method annotation, for comparison here is the recommended way for clearing the Hibernate second level cache.
Also have a look at this very well written blog post: Truly Understanding the Hibernate Second Level and Query caches.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With