Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement caching Spring method level annotations vs Hibernate second level cache

I am working on implementing caching of certain static data.

I have two approaches :

  • Use method level caching using Spring framework annotations.
  • Enable 2nd level cache so hibernate manages caching of the data

Which of these approaches works best ? What are the things I must consider ?

like image 596
souser Avatar asked Feb 03 '14 20:02

souser


1 Answers

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.

like image 144
Angular University Avatar answered Oct 20 '22 06:10

Angular University