Bird
0
0

You want to cache the result of a method that returns a list of users filtered by role. Which is the best way to use Redis caching in Spring Boot to avoid caching empty or null results?

hard📝 Application Q15 of 15
Spring Boot - Caching
You want to cache the result of a method that returns a list of users filtered by role. Which is the best way to use Redis caching in Spring Boot to avoid caching empty or null results?
public List getUsersByRole(String role) {
    // fetch users
}
AUse @CachePut to always update cache
BUse @Cacheable with condition = "#result != null && !#result.isEmpty()"
CManually check and cache inside the method
DUse @Cacheable without any condition
Step-by-Step Solution
Solution:
  1. Step 1: Understand caching empty results issue

    Caching empty or null results wastes cache space and may cause stale data.
  2. Step 2: Use @Cacheable condition attribute

    Adding condition "#result != null && !#result.isEmpty()" caches only meaningful results.
  3. Final Answer:

    Use @Cacheable with condition = "#result != null && !#result.isEmpty()" -> Option B
  4. Quick Check:

    Condition filters empty cache entries [OK]
Quick Trick: Use @Cacheable condition to skip empty results [OK]
Common Mistakes:
  • Caching all results including empty lists
  • Manually caching inside method instead of annotation
  • Using @CachePut which always updates cache

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes