3 回答

TA貢獻1712條經驗 獲得超3個贊
你需要做這樣的事情。請記住,這種方法有助于部分對象更新。這意味著如果您的對象(在 RequestBody 中)不包含某些字段(field==null),那么該字段將保持不變。
@PutMapping("user/{id}")
public boolean updateUser(@PathVariable id, @RequestBody User user) {
User currentUser = userRepo.findOne(id);
user = (User) PersistenceUtils.partialUpdate(currentUser, user);
return userRepo.save(user);
}
public class PersistenceUtils {
public static Object partialUpdate(Object dbObject, Object partialUpdateObject){
String[] ignoredProperties = getNullPropertyNames(partialUpdateObject);
BeanUtils.copyProperties(partialUpdateObject, dbObject, ignoredProperties);
return dbObject;
}
private static String[] getNullPropertyNames(Object object) {
final BeanWrapper wrappedSource = new BeanWrapperImpl(object);
return Stream.of(wrappedSource.getPropertyDescriptors())
.map(FeatureDescriptor::getName)
.filter(propertyName -> wrappedSource.getPropertyValue(propertyName) == null)
.toArray(String[]::new);
}
}

TA貢獻1777條經驗 獲得超3個贊
你可以參考這個關于 PATCH vs PUT 的問題。
假設您只是在更改用戶的在線狀態。在這種情況下,最好使用 PATCH 并將更改反映在路徑變量上。
例如:
@PatchMapping("user/{id}/{status}")
public boolean setStatus(@PathVariable id, @PathVariable status) {
User currentUser = userRepo.findOne(id);
currentUser.setStatus(status);
userRepo.save(currentUser);
// ...
}
如果打算對未定義數量的字段進行更改,您可以使用 PUT,在請求正文中包含數據并使用 DTO 模式。你可以在網上找到很多關于 DTO 模式的例子。在這種情況下,代碼如下。
@PatchMapping("user/{id}")
public boolean updateUser(@PathVariable id, @RequestBody UserDTO userDTO) {
// UserMapper is the mapper class which returns you a new User
// populated with the data provided in the data transfer object.
User user = UserMapper.makeUser(userDTO);
userRepo.update(id, user);
// ...
}
添加回答
舉報