ror roro
ror roro

Reputation: 317

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

I want to update specific data only name field for a restaurant object. The way I want to make it that if a field is empty or null, just leave the old value.

Is there any good solution?

Note that I'm making a rest api app with Spring Boot.

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

My post update 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;
} 

Upvotes: 1

Views: 5586

Answers (1)

Chris Savory
Chris Savory

Reputation: 2755

This is very similar to this question:

Spring REST partial update with @PATCH method

In REST, a POST is usually for resource creation, not updates. A PUT method is usually used for updates when you want to update the entire resource. And a PATCH method is used for partial updates.

You want to use a PATCH and then only update the fields that are present in the request body.

It's a little easier if you change your @RequestBody to a Map instead of Restaurant because if you use Restaurant you can't tell if the client is trying to set the value to null or not.

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

Upvotes: 2

Related Questions