SpringCache: Exploring the Usage of @CachePut Annotation in Java Learning
In the previous discussion, we covered the usage and parameter explanations of @CacheEvict. Now, let's delve into the usage of @CachePut in the context of SpringCache. Background: When working with caching in our daily routines, it's not only about adding and evicting caches but also about updating them. How can we achieve cache updates in SpringCache? Indeed, @CachePut comes to our rescue. In a way, you can think of @CachePut as a trigger. While this analogy may not be entirely accurate, it aids our understanding. Every time we invoke a method annotated with @CachePut, it acts as a trigger to either clear the specified key's cache or update it. Let's explore the logic behind these two annotations: @Cacheable: Look up the cache—return if found—execute the method body if not found—cache the result. @CachePut: Execute the method body—cache the result. Different logic is executed based on the return result. If the result is null, a second database query is triggered when we subsequently query the same key. This scenario is akin to how @CacheEvict annotation operates. When the result is not null, it initiates the cache update operation for that key, with the updated cache value being the returned data.