How to cache results of a Spring Data JPA query method without using query cache?

后端 未结 3 1299
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-12 20:00

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

3条回答
  •  执念已碎
    2020-12-12 20:23

    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;
       }
     }
    

提交回复
热议问题