Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out if key exist in cacheManager (org.springframework.cache.CacheManager)

Is there a way to see if a particular key exist in cacheManager (org.springframework.cache.CacheManager) as i am unable to find a way to do that as there is no containsKey option. I would appreciate if someone could show me a way to check if a key exist in cacheManager. Below are few things i have tried so far -

Cache cache=null;
for (String name : cacheManager.getCacheNames()) {
    cache=cacheManager.getCache(name);
    System.out.println("-------------->"+cache.get("dummyCache").get()); //this will give me null pointer exception as there is no dummyCache 
    }

I would like add if/else check to see if a dummyCachekey exist in cache

like image 241
Jon Abraham Avatar asked Apr 09 '26 17:04

Jon Abraham


1 Answers

You can simply check the value returned by Cache.get for null.

From the relevant documentation (emphasis by me):

Returns the value to which this cache maps the specified key, contained within a Cache.ValueWrapper which may also hold a cached null value. A straight null being returned means that the cache contains no mapping for this key.

So

  • cache.get("foo") == null means: The key "foo" does not exist in the cache
  • cache.get("foo").get() == null means: The key "foo" does exist in the cache, but its value is null
like image 83
Marvin Avatar answered Apr 21 '26 05:04

Marvin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!