Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
  • looks up in the cache based on the key
  • if found return the result from cache
  • if not found evaluates method
  • updates the cache
  • return the result

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

What I want instead is just to

  • Look up in the cache based on key
  • if found return the result from cache
  • if not found return null

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

like image 402
Prashant Bhate Avatar asked Apr 22 '15 15:04

Prashant Bhate


1 Answers

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
like image 140
Prashant Bhate Avatar answered Oct 27 '22 10:10

Prashant Bhate