【问题标题】:CachePut how to get and Id of returned value?CachePut如何获取返回值和Id?
【发布时间】:2021-10-30 20:52:48
【问题描述】:
@CachePut(value = "dishDTOs", key = "IDOFTHERETURNEDVALUE")
@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));
}

ID 由数据库分配,因此我需要以某种方式将其作为键。

【问题讨论】:

    标签: java spring caching


    【解决方案1】:

    SpeL 可以使用#result 访问返回的对象,您可以使用. 和字段名称访问对象参数。例如

    @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

    【讨论】:

      猜你喜欢
      • 2013-06-25
      • 1970-01-01
      • 2020-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多