I have a Spring Boot app with Spring Data JPA (hibernate backend) repository classes. I\'ve added a couple custom finder methods, some with specific @Query
anno
The reason the code you have is not working is that @Cache
is not intended to work that way. If you want to cache the results of a query method execution, the easiest way is to use Spring's caching abstraction.
interface PromotionServiceXrefRepository extends PagingAndSortingRepository {
@Query("…")
@Cacheable("servicesByCustomerId")
Set findByCustomerId(int customerId);
@Override
@CacheEvict(value = "servicesByCustomerId", key = "#p0.customer.id")
S save(S service);
}
This setup will cause results of calls to findByCustomerId(…)
be cached by the customer identifier. Note, that we added an @CacheEvict
to the overridden save(…)
method, so that the cache we populate with the query method is evicted, whenever an entity is saved. This probably has to be propagated to the delete(…)
methods as well.
Now you can go ahead an configure a dedicated CacheManager
(see the reference documentation for details) to plug in whichever caching solution you prefer (using a plain ConcurrentHashMap
here).
@Configuration
@EnableCaching
class CachingConfig {
@Bean
CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
cacheManager.addCaches(Arrays.asList(new ConcurrentMapCache("servicesByCustomerId)));
return cacheManager;
}
}