@Cacheable throws error Null key returned for cache operation

Viewed 472

Update:

tried key="#p0" , does not work

Trying to implement Redis with spring boot to cache my products, but I faced the problem, appreciate for any help

java.lang.IllegalArgumentException: Null key returned for cache operation (maybe you are using named params on classes without debug info?)

Controller

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/products")
public class ProductController {
    
    @Autowired
    ProductService productService;
    
    @GetMapping("/")
    public ResponseEntity<?> getAll() {

        List<Product> products = productService.findAll();
     
        return ResponseEntity.ok(products);
    }

}

Service

@Cacheable(value = "product", key = "#productId")
public List<Product> findAll() {
        return productRepository.findAll();
}

@EnableCaching annotation has also been put in the main class

2 Answers

The value of key should match the name of one of the arguments to the method annotated with @Cacheable, findAll. As findAll has no arguments there is nothing to use as a key.

https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/html/cache.html#cache-annotations-cacheable-key


A simple way to "cache" all the products in memory is just to store the result from the first call to productRepository.findAll() in an instance variable.

class ProductService {
  
  private List<Product> productCache;

  public List<Product> findAll() {
    if (productCache == null) {
      productCache = productRepository.findAll();
    }
    return productCache;
  }
}

To fill your product cache with your List<Product> from the repository you could invoke the CacheManager programmatically:

@Autowired CacheManager cacheManager;

public List<Product> findAll() {
    List<Product> products = productRepository.findAll();
    for (Product product : products) {
        cacheManager.getCache("product").put(product.getProductId(), product);
    }
    return products;
}
Related