我希望在findOne方法中添加“Cacheable”注释,并在删除或发生方法时清除缓存。
我该怎么做?
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个要点遗漏:
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.
save
and delete
should be CachePut
, and findAll
should be both Cacheable
and CacheEvict
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 {
}
findOne(ID id)
delete(T entity)
delete(Iterable<? extends T> entities)
deleteAll()
delete(ID id)
save
方法中使用了@CacheEvict
?为什么不使用@CachePut
呢?保存操作不会正确更新缓存,因此在保存后(假设缓存仍然存在)不需要运行@Cacheable
吗? - taylorcressy@CacheConfig
注释Repo
,以便将cache
名称放在CachingDao
之外。 - oak@Cache*
注解... https://github.com/spring-projects/spring-data-examples/blob/master/jpa/example/src/main/java/example/springdata/jpa/caching/CachingUserRepository.java - Snekse