Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 2 of 10 · Caching, Async & Scheduling
Interview question

What is the difference between @Cacheable, @CachePut, and @CacheEvict? @Cacheable, @CachePut और @CacheEvict में क्या अंतर है?

Answer

@Cacheable checks the cache before running the method and skips execution entirely on a cache hit. @CachePut always runs the method and then updates the cache with the returned value — used when you need the method to always execute (e.g. an update operation) while still keeping the cache in sync with the latest value.

@CacheEvict removes one or more entries from the cache, typically called on delete or update operations so stale data isn't served afterward; setting allEntries = true clears the entire cache region instead of a single key, useful when many entries could be invalidated by one change.

@CachePut(value = "products", key = "#product.id")
public Product updateProduct(Product product) {
    return productRepository.save(product); // always executes, cache is refreshed
}

@CacheEvict(value = "products", key = "#id")
public void deleteProduct(Long id) {
    productRepository.deleteById(id);
}

@Cacheable मेथड चलाने से पहले कैश जाँचता है और कैश हिट पर एक्ज़ीक्यूशन पूरी तरह छोड़ देता है। @CachePut हमेशा मेथड चलाता है और फिर रिटर्न किए गए वैल्यू से कैश को अपडेट करता है — तब उपयोग होता है जब मेथड को हमेशा चलना ज़रूरी हो (जैसे अपडेट ऑपरेशन)।

@CacheEvict कैश से एक या अधिक एंट्रीज़ को हटाता है, आमतौर पर डिलीट या अपडेट ऑपरेशन्स पर कॉल किया जाता है; allEntries = true सेट करने से एक सिंगल की के बजाय पूरा कैश रीजन साफ हो जाता है।

@CachePut(value = "products", key = "#product.id")
public Product updateProduct(Product product) {
    return productRepository.save(product);
}

@CacheEvict(value = "products", key = "#id")
public void deleteProduct(Long id) {
    productRepository.deleteById(id);
}

Was this answer clear?