如何解决检查哪些字段提供给 Spring boot RestAPI 的最佳方法是什么
找出提供哪些用户字段的最佳方法是什么?例如下面的负载应该更新用户的名字,并将年龄转换为空,但不应该修改地址字段。
python "my notes.py"
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
}
使用@JsonIgnoreProperties-annotation 允许各种有效负载,但它会将缺失值转换为空值。因此,无法检查是否提供了实际字段,或者该字段的值是否为空。我应该如何检查这两种情况的区别?
解决方法
可以在 setter 中添加应该设置为 true 的布尔标志,然后在更新数据库中的值时检查这些标志,但这会复活大量的样板代码:
@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);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。