我有同样的问题,正如Deinum先生所指出的,答案是否定的,您不能使用save。 主要问题是Spring Data不知道如何处理null。 是否设置了空值,还是因为需要将其删除而设置了空值?
现在从您的问题来看,我认为您也有同样的想法,那就是保存将使我避免手动设置所有更改的值。
那么有可能避免所有的手动映射吗? 好吧,如果您选择遵循空值始终表示“未设置”的约定,并且您拥有原始的模型ID,则可以。您可以使用Springs BeanUtils来避免自己进行任何映射。
您可以执行以下操作:
读取现有对象
使用BeanUtils复制值
保存对象
现在,Spring的BeanUtils实际不支持不复制空值,因此它将覆盖现有模型对象上未设置空值的任何值。 幸运的是,这里有一个解决方案:
如何使用springframework BeanUtils copyProperties忽略空值?
因此,将所有这些放在一起,最终会得到这样的结果
@RequestMapping(value = "/rest/user", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity> updateUser(@RequestBody User user) {
User existing = userRepository.read(user.getId());
copyNonNullProperties(user, existing);
userRepository.save(existing);
// ...
}
public static void copyNonNullProperties(Object src, Object target) {
BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
}
public static String[] getNullPropertyNames (Object source) {
final BeanWrapper src = new BeanWrapperImpl(source);
java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set emptyNames = new HashSet();
for(java.beans.PropertyDescriptor pd : pds) {
Object srcValue = src.getPropertyValue(pd.getName());
if (srcValue == null) emptyNames.add(pd.getName());
}
String[] result = new String[emptyNames.size()];
return emptyNames.toArray(result);
}