How to add cache feature in Spring Data JPA CRUDRepository

后端 未结 4 711
半阙折子戏
半阙折子戏 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:23

    virsir, there is one more way if you use Spring Data JPA (using just interfaces). Here what I have done, genereic dao for similar structured entities:

    public interface CachingDao extends JpaRepository, JpaSpecificationExecutor {
    
    @Cacheable(value = "myCache")
    T findOne(ID id);
    
    @Cacheable(value = "myCache")
    List findAll();
    
    @Cacheable(value = "myCache")
    Page findAll(Pageable pageable);
    
    ....
    
    @CacheEvict(value = "myCache", allEntries = true)
     S save(S entity);
    
    ....
    
    @CacheEvict(value = "myCache", allEntries = true)
    void delete(ID id);
    }
    

提交回复
热议问题