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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30964266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:54:30  来源:igfitidea点击:

How should I use @Cacheable on spring data repositories

javaspring-bootspring-data

提问by Hanan Bareket

When using, for example, MongoRepositorythere are some methods which I would like to mark as @Cacheablesuch as insert(entity)or findOne(id). Since it's a Spring repository and not mine, how should I use @Cacheableon those methods?

例如,在使用时,MongoRepository我想将某些方法标记@Cacheableinsert(entity)findOne(id)。由于它是一个 Spring 存储库而不是我的,我应该如何使用@Cacheable这些方法?

采纳答案by kryger

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 exampleI included in one of my comments)

(请注意,它基于我在其中一条评论中包含的官方示例

回答by Dragan Bozanovic

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.

这种方法的另一个好处是您可以使用单个声明使多个方法可缓存。