【发布时间】: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