Bird
0
0

Which approach correctly uses @CachePut to achieve this, assuming the method signature is public User updateEmail(Long userId, String newEmail)?

hard📝 Application Q15 of 15
Spring Boot - Caching
You have a method that updates a user's email and you want to ensure the cache entry for that user is updated immediately after the change. Which approach correctly uses @CachePut to achieve this, assuming the method signature is public User updateEmail(Long userId, String newEmail)?
A@CachePut(value = "users", key = "#userId") public User updateEmail(Long userId, String newEmail) { User user = userRepository.findById(userId); user.setEmail(newEmail); userRepository.save(user); return user; }
B@CachePut(value = "users", key = "#newEmail") public User updateEmail(Long userId, String newEmail) { User user = userRepository.findById(userId); user.setEmail(newEmail); userRepository.save(user); return user; }
C@CachePut(value = "users") public void updateEmail(Long userId, String newEmail) { User user = userRepository.findById(userId); user.setEmail(newEmail); userRepository.save(user); }
D@CachePut(key = "#userId") public User updateEmail(Long userId, String newEmail) { User user = userRepository.findById(userId); user.setEmail(newEmail); userRepository.save(user); return user; }
Step-by-Step Solution
Solution:
  1. Step 1: Verify correct cache name and key usage

    @CachePut(value = "users", key = "#userId") public User updateEmail(Long userId, String newEmail) { User user = userRepository.findById(userId); user.setEmail(newEmail); userRepository.save(user); return user; } uses 'value = "users"' and key '#userId', correctly identifying the cache and key.
  2. Step 2: Check method return and update logic

    @CachePut(value = "users", key = "#userId") public User updateEmail(Long userId, String newEmail) { User user = userRepository.findById(userId); user.setEmail(newEmail); userRepository.save(user); return user; } returns the updated User object, which is necessary for @CachePut to update the cache. Other options either use wrong key, no return, or missing cache name.
  3. Final Answer:

    @CachePut(value = "users", key = "#userId") public User updateEmail(Long userId, String newEmail) { User user = userRepository.findById(userId); user.setEmail(newEmail); userRepository.save(user); return user; } -> Option A
  4. Quick Check:

    Return updated object and use correct cache name and key [OK]
Quick Trick: Return updated object and use correct cache name and key [OK]
Common Mistakes:
  • Using wrong key expression
  • Not returning updated object
  • Omitting cache name in annotation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes