0
votes

I have a Model object like this -

class ProductDTO {
    int id;
    String code;
    String description;

   //getters and setters go here
}

I am trying to use Spring 4 with ehcache in a web service with code like this -

class ProductServiceImpl implements ProductService {

     List<ProductDTO> getAllProducts() {
         //Query to data layer getting all products
     }

     String getProductDescriptionById(int id) {
          //Query to data layer getting product by id
     }

     @Cacheable("prodCache")
     String getProductDescriptionByCode(String code) {
          //Query to data layer getting product by code
     }
}

The caching works fine on the method getProductDescriptionByCode() which has the cacheable annotation. Every time getProductDescriptionById() or getProductDescriptionByCode() is called, if there is a cache miss, I want to get all products (may be using getAllProducts() but not necessarily) and cache them so that the next time, I can retrieve any of the products. What additions or changes should I make to the annotations or code?

1

1 Answers

2
votes

So when you retrieve all the products using getAllProducts(), you need to iterate for each and put them in the cache using @CachePut. You need to separte cacheput function once to put description by code and other by id.

List<ProductDTO> getAllProducts() {
         List<ProductDTO> productList //get the list from database
         for(ProductDTO product : productList) {
             putProductDescriptionInCache(product.getDescription(), product.getCode());
          }
}

  @CachePut(value = "prodCache", key = "#Code")
   String putProductDescriptionInCache(String description, String Code){
    return description;
}