Spring boot cache on Response DTO

80 views Asked by At

I have written below function to get All the pokemons. Now I want to add the functionality to cache the pokemons by id which is coming from the list. I am using Simple cache for Caching.

Dependency:

implementation 'org.springframework.boot:spring-boot-starter-cache'

Cache Config :

@Component
public class SimpleCacheCustomizer implements CacheManagerCustomizer<ConcurrentMapCacheManager> {
    @Override
    public void customize(ConcurrentMapCacheManager cacheManager) {
        cacheManager.setCacheNames(List.of("pokemons"));
    }
}

Cache Function :

public interface PokemonCustomRepository {
    @Cacheable(value = "pokemons", key = "#result.id")
    List<Pokemon> getPokemonByNameAndType(String name, String types, int limit, Long skip, String generation, String sort);
}

I tried using above code, it gave me below error.

EL1012E: Cannot index into a null value

I tried below code :

public interface PokemonCustomRepository {
    @Cacheable(value = "pokemons", key = "#result?.each?.id", unless = "#result == null")
    List<Pokemon> getPokemonByNameAndType(String name, String types, int limit, Long skip, String generation, String sort);
}

Getting :

java.lang.IllegalArgumentException: Null key returned for cache operation (maybe you are using named params on classes without debug info?) Builder[public java.util.List api.pokedex.repository.custom.impl.PokemonCustomRepositoryImpl.getPokemonByNameAndType(java.lang.String,java.lang.String,int,java.lang.Long,java.lang.String,java.lang.String)] caches=[pokemons] | key='#result?.each?.id' | keyGenerator='' | cacheManager='' | cacheResolver='' | condition='' | unless='#result == null' | sync='false'

So my question is, can we cache the data based on the response coming ?
If yes, how can we do it ?
And if No, is there any way to do it using spring and not creating the own cache by Map and invoking it every time manually to check for cache hit ?

0

There are 0 answers