0
0
Spring Bootframework~5 mins

@CachePut for updating cache in Spring Boot

Choose your learning style9 modes available
Introduction

@CachePut helps keep your cache updated when you change data. It runs the method and then updates the cache with the new result.

When you want to update cached data after saving or changing it in the database.
When you want to make sure the cache always has the latest version of an object.
When you update an item and want the cache to reflect that change immediately.
When you want to avoid stale data in your cache after modifying data.
When you want to update cache without skipping the method execution.
Syntax
Spring Boot
@CachePut(value = "cacheName", key = "#key")
public ReturnType methodName(Parameters) {
    // method logic
}

value is the name of the cache to update.

key defines which cache entry to update, often using method parameters.

Examples
This updates the cache named 'users' with the user object using the user's id as the key.
Spring Boot
@CachePut(value = "users", key = "#user.id")
public User updateUser(User user) {
    // update user in database
    return user;
}
Updates the 'products' cache entry for the given product id after updating the product.
Spring Boot
@CachePut(value = "products", key = "#id")
public Product updateProduct(Long id, Product product) {
    // update product in database
    return product;
}
Sample Program

This service method updates a user and then updates the cache entry for that user using @CachePut.

The cache key is the user's id, so the cache always has the latest user data.

Spring Boot
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @CachePut(value = "users", key = "#user.id")
    public User updateUser(User user) {
        // Imagine this updates the user in a database
        System.out.println("Updating user in database: " + user);
        return user; // Return updated user to update cache
    }
}

record User(Long id, String name) {}

// Example usage:
// UserService service = new UserService();
// User updated = service.updateUser(new User(1L, "Alice Updated"));
// Output:
// Updating user in database: User[id=1, name=Alice Updated]
OutputSuccess
Important Notes

@CachePut always runs the method, unlike @Cacheable which may skip method execution if cache exists.

Make sure the method returns the updated object so the cache can store it.

Use proper keys to avoid cache collisions or wrong updates.

Summary

@CachePut updates cache after method runs.

Use it when you want fresh data in cache after changes.

It needs a cache name and a key to know what to update.