Search code examples
spring-bootjava-8spring-cache

How @Cacheable works when the cached record gets updated


I was referring link for implementing spring cache.

My scenario is something like this.

@Cacheable("employees")
public List<Employee> getEmployeeDetails( int empId ){
    
}

So I understand that once the data is cached then it won't fetch data from DB. In this case what will happen if another service method updateEmployee(int empid) updates the record. How can I get an updated record ? How @Cacheable works when the cached record gets updated ?

Anything wrong in my understanding ?


Solution

  • Your understanding is somehow correct. In the above example,

    @Cacheable("employees")
    

    will put the values of employees in cache.

    If you have some service methods which will update values or make the object stale, then you need to use @CacheEvict or @CachePut.

    Let's say you have another service method which saves the employee.

    public void saveEmployee(Employee employee){
    //
    }
    

    Here you have to use either @CacheEvict or @CachePut.

    You can see the difference between them in the link that you are following.

    You can find more in this SO post as well.