简体   繁体   English

我应该如何在 Spring 数据存储库上使用 @Cacheable

[英]How should I use @Cacheable on spring data repositories

When using, for example, MongoRepository there are some methods which I would like to mark as @Cacheable such as insert(entity) or findOne(id) .例如,在使用MongoRepository ,我想将一些方法标记为@Cacheable例如insert(entity)findOne(id) Since it's a Spring repository and not mine, how should I use @Cacheable on those methods?由于它是一个 Spring 存储库而不是我的,我应该如何在这些方法上使用@Cacheable

Not sure how you're actually using MongoRepository , you seem to be suggesting you're using it directly (it's often a good idea to include your code in the question) , but the reference documentation explains the basics of working with this interface (and all repository interfaces in Spring Data, as a matter of fact): "§ 6.1. Core concepts" :不确定您实际如何使用MongoRepository ,您似乎建议您直接使用它(在问题中包含您的代码通常是个好主意) ,但参考文档解释了使用此接口的基础知识(和事实上,Spring Data 中的所有存储库接口): “§ 6.1. 核心概念”

(...) This interface acts primarily as a marker interface to capture the types to work with and to help you to discover interfaces that extend this one. (...)此接口主要用作标记接口,用于捕获要使用的类型并帮助您发现扩展此接口的接口。 (...) (……)

Your custom repository would be something like:您的自定义存储库将类似于:

public interface SomeTypeMongoRepository extends MongoRepository<SomeType, Long> {
    @Override
    @CacheEvict("someCache")
    <S extends SomeType> S insert(S entity);

    @Override
    @Cacheable("someCache")
    SomeType findOne(Long id);
}

(note that it's based on the official example I included in one of my comments) (请注意,它基于我在其中一条评论中包含的官方示例

One of the options could be to do it in xml, as explained in the docs .选项之一可能是在 xml 中进行,如docs中所述。

Another benefit of this approach is that you can make multiple methods cacheable with a single declaration.这种方法的另一个好处是您可以使用单个声明使多个方法可缓存。

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

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