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