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

时间:2012-12-17 12:48:07

标签: spring hibernate caching jpa jdbc

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

我该怎么做?

4 个答案:

答案 0 :(得分:12)

virsir,如果您使用Spring Data JPA(仅使用接口),还有一种方法。这就是我所做的,类似结构化实体的genereic dao:

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

答案 1 :(得分:6)

我认为@7的答案基本上是正确的,但有2个缺失点:

  1. 我们无法定义通用接口,我担心我们必须单独声明每个具体接口,因为注释不能被继承,我们需要为每个存储库设置不同的缓存名称。

  2. savedelete应为CachePutfindAll应为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);
    }
    
  3. Reference

答案 2 :(得分:4)

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


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 {

}

答案 3 :(得分:2)

尝试提供MyCRUDRepository(接口和实现),如下所述:Adding custom behaviour to all repositories。然后,您可以覆盖并添加这些方法的注释:

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