简体   繁体   English

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

[英]How to add cache feature in Spring Data JPA CRUDRepository

I want to add "Cacheable" annotation in findOne method, and evict the cache when delete or happen methods happened. 我想在findOne方法中添加“Cacheable”注释,并在删除或发生方法时逐出缓存。

How can I do that ? 我怎样才能做到这一点 ?

virsir, there is one more way if you use Spring Data JPA (using just interfaces). virsir,如果您使用Spring Data JPA(仅使用接口),还有一种方法。 Here what I have done, genereic dao for similar structured entities: 这就是我所做的,类似结构化实体的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);
}

I think basically @seven's answer is correct, but with 2 missing points: 我认为基本上@七的答案是正确的,但有两个缺点:

  1. 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. 我们无法定义通用接口,我担心我们必须单独声明每个具体接口,因为注释不能被继承,我们需要为每个存储库提供不同的缓存名称。

  2. save and delete should be CachePut , and findAll should be both Cacheable and CacheEvict 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); } 

Reference 参考

I solved the this in the following way and its working fine 我用以下方式解决了这个问题并且工作正常


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 {

}

Try provide MyCRUDRepository (an interface and an implementation) as explained here: Adding custom behaviour to all repositories . 尝试提供MyCRUDRepository(接口和实现),如下所述: 向所有存储库添加自定义行为 Then you can override and add annotations for these methods: 然后,您可以覆盖并添加这些方法的注释:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM