【发布时间】:2012-12-04 13:37:36
【问题描述】:
我想在 findOne 方法中添加“Cacheable”注解,并在 delete 或发生方法发生时驱逐缓存。
我该怎么做?
【问题讨论】:
标签: spring hibernate caching jpa jdbc
我想在 findOne 方法中添加“Cacheable”注解,并在 delete 或发生方法发生时驱逐缓存。
我该怎么做?
【问题讨论】:
标签: spring hibernate caching jpa jdbc
virsir,如果您使用 Spring Data JPA(仅使用接口),还有另一种方法。这是我所做的,用于类似结构化实体的通用 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);
}
【讨论】:
@CacheEvict作为方法save吗?为什么不使用@CachePut?不会保存它正确更新缓存,因此不需要@Cacheable 在保存后运行(假设缓存仍然存在)
@CacheConfig 注释Repo,因此cache 名称将在CachingDao 之外
@Cache* 注释 ...github.com/spring-projects/spring-data-examples/blob/master/jpa/…
我认为@seven 的回答基本上是正确的,但缺少 2 点:
我们不能定义一个通用接口,恐怕我们必须单独声明每个具体接口,因为注释不能被继承,我们需要为每个存储库有不同的缓存名称。
save 和 delete 应该是 CachePut,findAll 应该同时是 Cacheable 和 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 {
}
【讨论】:
尝试提供 MyCRUDRepository(一个接口和一个实现),如下所述:Adding custom behaviour to all repositories。然后您可以覆盖并为这些方法添加注释:
findOne(ID id)
delete(T entity)
delete(Iterable<? extends T> entities)
deleteAll()
delete(ID id)
【讨论】: