如何在Spring Data JPA CRUD中添加缓存功能



我想在findOne方法中添加"可缓存"注释,并在发生删除或发生方法时逐出缓存。

我该怎么做?

virsir,如果你使用Spring Data JPA(只使用接口),还有另一种方法。在这里,我所做的是,为类似的结构化实体提供通用道:

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

基本上@seven的答案是正确的,但缺少 2 点:

  1. 我们不能定义一个通用接口,恐怕我们必须单独声明每个具体的接口,因为注释不能被继承,我们需要为每个仓库有不同的缓存名称。

  2. savedelete应该是CachePut的,findAll应该既CacheableCacheEvict

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

参考

我通过以下方式解决了这个问题,并且工作正常


public interface BookRepositoryCustom {
    Book findOne(Long id);
}

public class BookRepositoryImpl extends SimpleJpaRepository<Book,Long> implements BookRepositoryCustom {
    @Inject
    public BookRepositoryImpl(EntityManager entityManager) {
        super(Book.class, entityManager);
    }
    @Cacheable(value = "books", key = "#id")
    public Book findOne(Long id) {
        return super.findOne(id);
    }
}

public interface BookRepository extends JpaRepository<Book,Long>, BookRepositoryCustom {
}

尝试提供 MyCRUDRepository(接口和实现),如下所述:向所有存储库添加自定义行为。然后,您可以重写并添加这些方法的注释:

findOne(ID id)
delete(T entity)
delete(Iterable<? extends T> entities)
deleteAll() 
delete(ID id) 

最新更新