Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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). Since it's a Spring repository and not mine, how should I use @Cacheable on those methods?

like image 241
Hanan Bareket Avatar asked Jun 21 '15 11:06

Hanan Bareket


People also ask

How to cache data in Spring Boot?

Spring boot Cache using @EnableCaching and @Cachable 1 Enable Caching in Spring App (SpringApplication.java) 2 Cache data in methods using @Cacheable (StudentService.java) Annotation indicating that the result of invoking a method (or all methods in a class) can be cached. 3 Application.yml 4 StudentController.java 5 Student.java 6 pom.xml. ...

What is @cacheable annotation in Spring Framework?

Spring Framework has built-in classes and annotations to help developers dealing with caching. The @Cacheable annotation is one of them, it is the most widely used Spring cache-related annotations. In this article, we will go on the usage of this annotation and important keynotes about it.

Where does the spring-context cache reside?

The core caching abstraction provided by Spring resides in the spring-context module. So when using Maven, our pom.xml should contain the following dependency:

How do I create a spring cache abstraction?

This guide assumes that you chose Java. Click Dependencies and select Spring cache abstraction. Click Generate. Download the resulting ZIP file, which is an archive of a web application that is configured with your choices.


1 Answers

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":

(...) 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)

like image 107
kryger Avatar answered Sep 28 '22 14:09

kryger