You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

服务层createOrUpdate方法能否仅用@CachePut注解?是否需搭配@Cacheable?

Answer to Your Caching Annotation Question

Great question! Let's break this down clearly based on how Spring's caching annotations work, especially for your createOrUpdate method scenario.

First, Let's Clarify the Core Differences

Let's start with what each annotation actually does—this is the key to answering your question:

  • @Cacheable: This is for read operations. It checks if the cache has an entry for the specified key first. If it exists, it returns the cached value without running the method. If not, it executes the method and stores the result in the cache.
  • @CachePut: This is for write operations (creates/updates). It always runs the method, then takes the result and updates the cache—either adding a new entry if the key didn't exist, or overwriting the old one.

Applying This to Your createOrUpdate Method

Your method's logic is straightforward: create a record if the ID doesn't exist, update it if the ID does exist. This is a write-focused method—you call it to modify data in the database, not just retrieve it.

Should You Use Only @CachePut?

Yes, this is the correct approach. Here's why:

  • When creating a new record: The method runs the insert logic, then @CachePut adds the new entity to the cache. The cache now holds the fresh data, which is exactly what you want.
  • When updating an existing record: The method runs the update logic against the database, then @CachePut overwrites the old cached entry with the updated entity. This keeps the cache perfectly in sync with the database.

Why You Don't Need @Cacheable

Adding @Cacheable alongside @CachePut would break your method's intended behavior:

  • If the ID already exists in the cache, @Cacheable would skip executing your method entirely. That means your update logic never runs against the database—you'd just return the old cached value instead of updating the record.
  • This directly contradicts the purpose of createOrUpdate, which is to modify the database regardless of the cache state.

Example Code to Illustrate

Here's how your service layer might look with the correct annotation setup:

@Service
public class YourEntityService {
    @Autowired
    private YourEntityRepository repository;

    // Only @CachePut is needed here
    @CachePut(value = "yourEntities", key = "#entity.id")
    public YourEntity createOrUpdate(YourEntity entity) {
        if (entity.getId() == null) {
            // Create new record
            return repository.save(entity);
        } else {
            // Update existing record
            YourEntity existing = repository.findById(entity.getId())
                .orElseThrow(() -> new RuntimeException("Entity not found"));
            // Copy updated fields to existing entity
            existing.setName(entity.getName());
            existing.setDescription(entity.getDescription());
            // ... handle other fields
            return repository.save(existing);
        }
    }

    // Use @Cacheable for your read/query methods
    @Cacheable(value = "yourEntities", key = "#id")
    public YourEntity getById(Long id) {
        return repository.findById(id)
            .orElseThrow(() -> new RuntimeException("Entity not found"));
    }
}

Final Takeaway

Stick with only @CachePut for your createOrUpdate method. It ensures your database operation always runs, and keeps the cache synchronized with the latest data. Reserve @Cacheable for your dedicated query methods, where you want to avoid hitting the database when data is already cached.

内容的提问来源于stack exchange,提问作者Prateek Narendra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:29:42