@cachePut for data update in list of object in spring boot

Viewed 835

Hi I am using Spring Boot Cache in my application. I am able to fetch data from db and cached that data.

 @Cacheable("employee")
public Optional<List<Employee>> employeeData(){
    log.info("Fetched employee details from DB and cached in memory!!");
    return employeeRepository.findActiveEmployee();
}

I want to delete or update or add new record in cached object.

How can I use @cachePut to update existing record or insert record or delete existing record based on some condition.

1 Answers

You can keep your original method as is to call it whenever you want to fetch data from cache. Note that the @Cacheable annotation does not execute the method's body if the cache with name "employee" is not empty, instead it returns the results from cache.

@Cacheable("employee")
public Optional<List<Employee>> employeeData(){
}

Then proceed in creating a new method annotated with @CachePut. Having in mind that @CachePut annotation will both execute the method as well as cache the results each and every time:

@CachePut(value="employee", condition="#name=='Tom'")
public Optional<List<Employee>> employeeDataCacheByName(String name){
    log.info("Fetched employee details from DB and cached in memory depending on condition!!");
    return employeeRepository.findActiveEmployee();
}

The above method will run the query every time and put into employee cache the results if the name argument is "Tom" (condition logic is up to you, this is just an example). This way cache is always updated with the results from the database (as long as the condition is truly evaluated).

For deleting (I don't think @CachePut can be used) maybe you can combine the @CacheEvict annotation, you can see an example in this Answer: https://stackoverflow.com/a/62488344/3635454

Related