Search code examples
hazelcastspring-cache

Can @CachePut annotation be put for createOrUpdate method?


I had a small doubt -

I have a method in my service layer that either creates a record if that ID isnt present or updates record if it is. Can i just put @CachePut annotation on the method? Or Should I also put @Cacheable anotation also on it


Solution

  • In this case you want to use @CachePut on your service method performing the create or update. For example...

    Assuming...

    class Customer {
    
      @Id
      Long id;
    
      ...
    }
    

    And given...

    @Service
    class CustomerService {
    
      CustomerRepository customerRepository;
    
      @CachePut("Customers", key="#customer.id")
      Customer createOrUpdate(Customer customer) {
        // validate customer
        // any business logic or pre-save operations
        return customerRepository.save(customer);
      }
    }
    

    @Cacheable is going perform a look-aside in the named cache before executing createOrUpdate(:Customer). If the Customer with ID already exists in the named cache, then Spring will return the "cached" Customer; Spring will not execute the create/update method in that case.

    However, if the identified Customer does not exist (or is invalid), Spring proceeds to execute the createOrUpdate(:Customer) method and then cache the result of the method.

    In the @CachePut case, Spring will always execute the createOrUpdate(:Customer) method. That is, Spring will not perform a look-aside to determine whether the Customer exists before executing the method, which is most likely what you want in the case of a create/update.

    Anyway, more information about declarative based Caching can be found in the Reference Guide. In particular, have a look at the @CachePut docs and compare that with the @Cacheable docs.

    Hope this helps! -John