【问题标题】:update specific data for an object using POST method in spring boot rest在 Spring Boot Rest 中使用 POST 方法更新对象的特定数据
【发布时间】:2021-02-23 13:45:37
【问题描述】:

我只想更新餐厅对象的特定数据name 字段。我想让它的方式是,如果一个字段是 empty 或 null,只需保留旧值。

有什么好的解决办法吗?

请注意,我正在使用 Spring Boot 制作一个 rest api 应用程序。

Restaurant.java:

@Entity
@NoArgsConstructor
@RequiredArgsConstructor
@Getter
@Setter
@ToString
public class Restaurant {

    @Id
    @GeneratedValue
    private long id;

    @NonNull
    @NotEmpty(message = "The restaurant must have a name")
    private String name;

    @NonNull
    @NotEmpty(message = "Please add a description for this restaurant")
    private String description;

    @NonNull
    @NotEmpty(message = "The restaurant must have a location")
    private String location;
}

我的帖子更新功能:

@PostMapping("/restaurant/{id}/update")
public Restaurant updateRestaurant(@PathVariable Long id, @RequestBody Restaurant restaurantDetails, BindingResult bindingResult) {     
    Optional<Restaurant> restaurantOptional = restaurantService.findById(id);

    if (restaurantOptional.isPresent()) {
        Restaurant restaurant = restaurantOptional.get();
        restaurant.setName(restaurantDetails.getName());
        restaurant.setLocation(restaurant.getLocation());
        restaurant.setDescription(restaurantDetails.getDescription());
        logger.info("restaurant information edited successfully");
        return restaurantService.save(restaurant);
    } else
        return null;
} 

【问题讨论】:

    标签: java spring spring-boot rest


    【解决方案1】:

    这与这个问题非常相似:

    Spring REST partial update with @PATCH method

    在 REST 中,POST 通常用于创建资源,而不是更新。当您想要更新整个资源时,通常使用 PUT 方法进行更新。并且使用 PATCH 方法进行部分更新。

    您想使用 PATCH,然后只更新请求正文中存在的字段。

    如果您将@RequestBody 更改为Map 而不是Restaurant,会更容易一些,因为如果您使用Restaurant,您无法判断客户端是否尝试将值设置为空。

        @PatchMapping("/restaurant/{id}/update")
    public Restaurant updateRestaurant(@PathVariable Long id, @RequestBody Map<String, Object> restaurantDetails, BindingResult bindingResult)
    {
           
                Optional<Restaurant> restaurantOptional = restaurantService.findById(id);
    
                if (restaurantOptional.isPresent()) {
                    Restaurant restaurant = restaurantOptional.get();
    
                    // loop through the map keys here and only update the values that are present in the map. 
    
                    logger.info("restaurant information edited successfully");
                    return restaurantService.save(restaurant);
                } else
                    return null;
            }
    

    【讨论】:

    • 我将答案从 PostMapping 注解更新为 PatchMapping
    猜你喜欢
    • 2020-02-04
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 2017-11-02
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多