检查哪些字段被提供给Spring引导RestAPI的最佳方法是什么



找出提供了哪些用户字段的最佳方法是什么?例如,以下有效载荷应该更新用户的名称,并将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。因此,无法检查是否提供了实际字段,或者字段的值是否为空。我应该如何检查这两种情况的差异?

可以添加布尔标志,这些标志应该在setters中设置为true,然后在更新DB中的值时检查这些标志,但这将恢复许多布尔板代码:

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

最新更新