Hanan Bareket
Hanan Bareket

Reputation: 195

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?

Upvotes: 13

Views: 17607

Answers (2)

kryger
kryger

Reputation: 13181

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)

Upvotes: 10

Dragan Bozanovic
Dragan Bozanovic

Reputation: 23562

One of the options could be to do it in xml, as explained in the docs.

Another benefit of this approach is that you can make multiple methods cacheable with a single declaration.

Upvotes: 1

Related Questions