检查哪些字段被赋予springbootpi的最佳方法是什么

uyhoqukh  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(324)

找出提供了哪些用户字段的最佳方法是什么?e、 g.下面的负载应该更新用户名,并将age转换为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;
  ...
}

使用@jsonignoreproperties注解允许各种有效负载,但它会将缺少的值转换为null。因此,无法检查提供的是实际字段还是字段值为空。我应该如何检查这两种情况的区别?

ncgqoxb0

ncgqoxb01#

可以在setters中添加布尔标志,将其设置为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);
    }
}

相关问题