I want to cache the response of the repository class which has the following methods:
@Cacheable(cacheNames = "books", key="#id") Book findById(Long Id); @CacheEvict(cacheNames = "books", key = "#id") void deleteById(Long id); @Cacheable(cacheNames = "books", key="#book.id") Book save(Book book); @Cacheable("books") List<Book> findAll();
Except the <strong>findAll()</strong> method, others are working as expected.
How to make <strong>findAll()</strong> to populate the <strong>books</strong> cache with <strong>book.id</strong> as key?Answer1:
Once more, this <a href="https://stackoverflow.com/questions/44529029/spring-cache-with-collection-of-items-entities" rel="nofollow">nearly identical question</a> keeps coming up over and over again with only slightly different expectations, this time when combined with SD <em>Repositories</em>, and specifically the
findAll() query method. And again, the answer is the same in each use case... you need to provide a customized <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/cache/CacheManager.html" rel="nofollow">
CacheManager</a> and <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/cache/Cache.html" rel="nofollow">
Cache</a> implementation for your caching provider (e.g. Ehcache, Redis or Hazelcast).
By default, OOTB, <em>Spring's Cache Abstraction</em> does not split up cached method array/collection type return values into separate entries in the targeted cache. You must handle this yourself.
See my last response for 1 example of how someone might go about handling this.