Prashant Bhate
Prashant Bhate

Reputation: 11087

How to make @Cacheable return null when not found in cache but do not cache the result?

Following @Cacheable annotation

@Cacheable(value="books", key="#isbn")
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)

So that next time this method is called with same arguments it will be fetched from cache.

What I want instead is just to

I don't want to update the cache in case of cache-miss, is there any way to do this using spring Annotation

Upvotes: 5

Views: 11208

Answers (1)

Prashant Bhate
Prashant Bhate

Reputation: 11087

Here is what I ended up with, trick was to use 'unless' to our advantage

@Cacheable(value="books", key="#isbn", unless = "#result == null")
public Book findBookFromCache(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
{
    return null;
}

this method

  • Looks up in the cache based on key
  • if found return the result from cache
  • if not found evaluates method that return null
  • return value is matched with unless condition (which always return true)
  • null value do not get cached
  • null value is returned to caller

Upvotes: 9

Related Questions