10. Query cache
Query cache
1. @Cacheable
Used to read from cache if available, otherwise executes the method and stores the result in cache.
When to use: For read-heavy operations (e.g., fetching data from DB).
Example:
@Cacheable("users")
public User getUserById(Long id) {
System.out.println("Fetching from DB...");
return userRepository.findById(id).orElse(null);
}
What happens:
- First call with `id = 1`: fetches from DB and caches the result.
- Second call with `id = 1`: returns result from cache, no DB hit.
2. @CachePut
Always executes the method and updates the cache with the result.
When to use: When data is updated, and cache should be refreshed.
Example:
@CachePut(value = "users", key = "#user.id")
public User updateUser(User user) {
return userRepository.save(user); // saves to DB and updates cache
}
What happens:
- Always hits DB.
- Updates the cache with new value.
3. @CacheEvict
Used to remove a cache entry or clear cache.
When to use: When data is deleted or changed, and cache needs to be cleared.
Example:
@CacheEvict(value = "users", key = "#id")
public void deleteUser(Long id) {
userRepository.deleteById(id); // removes from DB and cache
}
What happens:
- Deletes user from DB.
- Removes cache entry with matching `id`.
we can use any name for "users" in @Cacheable("users")
@Cacheable("myUserCache")
public User getUserById(Long id) { ... }
But:
This name must match in all related annotations (@CachePut, @CacheEvict, etc.) to work with the same cache.
It’s just an identifier for the cache region.
We should use as "user.id" because #user refers to the method parameter User user.
@CachePut(value = "users", key = "#user.id")
public User updateUser(User user) {
return userRepository.save(user); // saves to DB and updates cache
}
Annotation | DB Hit | Cache Used | Cache Updated | Use Case |
@Cacheable | No (if cached) | Yes | No | Fetch and cache result |
@CachePut | Yes | No | Yes | Update cache after method |
@CacheEvict | Yes | N/A | N/A (clears) | Remove from cache |
Comments
Post a Comment