mka
mka

Reputation: 111

@Cacheable() not returning proper cache

I am well aware that there are multiple questions on this topic, but I just can't get the sense of it. The problem seems to be that @CachePut does not add the new value to the @Cacheable list.

After debugging the problem I found out that the problem seems to be in the key.

Here is the code snippet

@CacheConfig(cacheNames = "documents")
interface DocumentRepository {

@CachePut(key = "#a0.id")
Document save(Document document);

@Cacheable()
List<Document> findAll();
}

So when I invoke the save method, the key being used for caching is incrementing integer, or 1,2,3... But when I try to get all documents, the cache uses SimpleKey[] as key. If I try to use the same key for @Cacheable, I get SpelEvaluationException, property 'id' cannot be found on null.

So what I am left with at the end is functional cache (the data is saved in the cache), but somehow I am not able to retrieve it. The underlying cache implementation is EhCache.

Upvotes: 0

Views: 599

Answers (1)

Stephane Nicoll
Stephane Nicoll

Reputation: 33151

I really don't understand what you are expecting here.

It looks like you expect your findAll method to return the full content of the cache named documents. I don't think there is anything in the documentation that can let you conclude that this feature exists (it does not). It is also very fragile. If we were implementing that, findAll would return different results based on the state of the cache. If someone would configure this cache to have a max size of 100 for instance. Or If the cache isn't warm-up on startup.

You can't expect a cache abstraction (or even a cache library) to maintain a synchronized view of "a list of objects". What findAll does is returning the entry that corresponds to a key with no argument (new SimpleKey by default).

Upvotes: 1

Related Questions