How to add cache feature in Spring Data JPA CRUDRepository

后端 未结 4 720
半阙折子戏
半阙折子戏 2020-12-31 04:27

I want to add \"Cacheable\" annotation in findOne method, and evict the cache when delete or happen methods happened.

How can I do that ?

4条回答
  •  死守一世寂寞
    2020-12-31 05:05

    I think basically @seven's answer is correct, but with 2 missing points:

    1. We cannot define a generic interface, I'm afraid we have to declare every concrete interface separately since annotation cannot be inherited and we need to have different cache names for each repository.

    2. save and delete should be CachePut, and findAll should be both Cacheable and CacheEvict

      public interface CacheRepository extends CrudRepository {
      
          @Cacheable("cacheName")
          T findOne(String name);
      
          @Cacheable("cacheName")
          @CacheEvict(value = "cacheName", allEntries = true)
          Iterable findAll();
      
          @Override
          @CachePut("cacheName")
          T save(T entity);
      
          @Override
          @CacheEvict("cacheName")
          void delete(String name);
      }
      

    Reference

提交回复
热议问题