简体   繁体   English

检查 Spring 引导 RestAPI 的字段的最佳方法是什么

[英]What is the best way to check which fields are given to the Spring boot RestAPI

What is the best way to find out which user fields are provided?找出提供了哪些用户字段的最佳方法是什么? eg the following payload should update the name of the user, and convert age to null but it should not modify the address-field.例如,下面的有效载荷应该更新用户的名字,并将年龄转换为 null 但它不应该修改地址字段。

curl -i -X PATCH http://localhost:8080/123 -H "Content-Type: application/json-patch+json" -d '{
    "name":"replace",
    "age":null
}'
@PatchMapping(path = "/{id}", consumes = "application/json-patch+json")
public ResponseEntity<User> updateUser(@PathVariable String id, @RequestBody User user) {
  ... handle user based on which fields are provided
}
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class User { 
  private String name;
  private Integer age;
  private String address;
  ...
}

Using @JsonIgnoreProperties-annotation allows various payloads but it converts missing values to nulls.使用 @JsonIgnoreProperties-annotation 允许各种有效负载,但它将缺失值转换为空值。 Therefore, there is no way to check is the actual field provided or is the field's value just null.因此,无法检查提供的实际字段还是该字段的值只是 null。 How should I check difference of those two cases?我应该如何检查这两种情况的区别?

It is possible to add boolean flags which should be set to true in the setters and then to check these flags when updating the values in the DB, but this will resurrect a lot of bolerplate code:可以添加 boolean 标志,这些标志应该在设置器中设置为 true,然后在更新 DB 中的值时检查这些标志,但这会复活很多 bolerplate 代码:

@Data
public class User { 
  private String name;
  private Integer age;
  private String address;
  
  @JsonIgnore
  private boolean nameSet = false;

  @JsonIgnore
  private boolean ageSet = false;

  @JsonIgnore
  private boolean addressSet = false;

  public void setName(String name) {
      this.name = name;
      this.nameSet = true;
  }
  // ... etc.
}
public ResponseEntity<User> updateUser(@PathVariable String id, @RequestBody User user) {
  //... handle user based on which fields are provided
    User db = userRepo.byId(id);

    boolean changed = user.isNameSet() || user.isAgeSet() || user.isAddressSet();

    if (changed) {
        if (user.isNameSet()) db.setName(user.getName());
        // etc.

        userRepo.save(db);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM