簡體   English   中英

在 spring 引導 rest 中使用 POST 方法更新 object 的特定數據

[英]update specific data for an object using POST method in spring boot rest

我想更新餐廳 object 的特定數據name字段。 我想讓它的方式是,如果一個字段為空或 null ,只需保留舊值。

有什么好的解決辦法嗎?

請注意,我正在使用 Spring 啟動 rest api 應用程序。

餐廳.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;
}

我的帖子更新 function:

@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;
} 

這與這個問題非常相似:

Spring REST 使用@PATCH 方法進行部分更新

在 REST 中,POST 通常用於資源創建,而不是更新。 當您想要更新整個資源時,通常使用 PUT 方法進行更新。 並且 PATCH 方法用於部分更新。

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

如果您將 @RequestBody 更改為Map而不是Restaurant會更容易一些,因為如果您使用Restaurant ,您無法判斷客戶端是否嘗試將值設置為 null。

    @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;
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM