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?
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. ...
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.
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:
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With