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

使用@CachePut注解时如何获取方法返回值的ID作为缓存key

解决方案

Spring Cache 内置了 SpEL 表达式变量 #result,可直接指向当前注解修饰方法的返回值,你只需要修改 @CachePut 的 key 属性值为 #result.你的ID字段名 即可。

示例修改后的代码

@CachePut(value = "dishDTOs", key = "#result.id")
@CacheEvict(cacheNames = "dishDTOList", allEntries = true)
public DishResponseDTO createDish(DishCreationDTO dishCreationDTO) {
    int restaurantId = dishCreationDTO.getRestaurantId();
    var restaurant = restaurantRepository.getById(restaurantId);

    var dish = DishMapper.toDish(dishCreationDTO, restaurant);
    return toDishResponseDTO(dishRepository.save(dish));
}

注意事项

  • 上述代码默认你的 DishResponseDTO 类中ID对应的字段名为 id,如果实际字段名是 dishId 等其他命名,将key属性里的id替换为实际字段名即可
  • 该方式仅在方法有非空返回值时生效,你的业务逻辑里方法固定返回保存后的DTO,不存在空指针风险

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 00:21:01