Search code examples
javaspring-bootcachingehcache-3

How to create multiple cache key in @Cacheable when parameter value is null


I am trying to create a cache key with multiple parameter values.

@Cacheable(cacheNames = "cache_name_", key = "#name + '_' + #id")
private JSONObject getData(String name, String id) throws Exception {

From the above scenario, I name is a mandatory field while id is optional. I want to create key in such a way that,

  1. If name = "test" and id = null, cache key must be cache_name_test
  2. If name = "test" and id = "2", cache key must be cache_name_test_2

Currently, the key is forming something like "cache_name_test_null" if the id is not passed in the parameter value

Is it possible to create such key with @Cacheable annotation?


Solution

  • Solution

    It's doable, but you need to wrap 2 @Cachable annotations in a @Caching annotation.

    @Caching(
          cacheable = {
                @Cacheable(cacheNames = "cache_name_", key = "#name + '_' + #id", condition = "#id != null"),
                @Cacheable(cacheNames = "cache_name_", key = "#name", condition = "#id == null")
          }
        )
    public JSONObject getData(String name, String id) throws Exception {
    

    Note on private methods

    You are using the @Caching annotation on a private method. This doesn't work. Those annotations only work on public methods being called from outside the class. See this Stack Overflow answer: https://stackoverflow.com/a/16899739/2082699