除了在spring-boot中执行null检查之外,还有更有效的方法来处理补丁请求更新吗



除了最初执行null检查之外,还有更好的更新方法吗?

@PatchMapping("/base/uri/{id}")
public void updateModel(@Valid @RequestBody Model newModel, @Pathvariable Long id) {
modelRepository.findById(id).map(model -> {
if (newModel.getParam1() != null) model.setParam1(newModel.getParam1());
if (newModel.getParam2() != null) model.setParam1(newModel.getParam2());
if (newModel.getParam3() != null) model.setParam1(newModel.getParam3());
if (newModel.getParam4() != null) model.setParam1(newModel.getParam4());
...
modelRespository.save(model);
}).orElseThrow(() -> MyNotFoundException());
}

您可以使用spring框架的BeanUtils添加要忽略的属性(在本例中为空属性(,如下所示:

import java.beans.FeatureDescriptor;
import java.util.stream.Stream;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
@PatchMapping("/base/uri/{id}")
public void updateModel(@Valid @RequestBody Model newModel, @Pathvariable Long id) {
modelRepository.findById(id).map(model -> {
String[] nulls = getNullPropertyNames(newModel);
// copy the newModel into model 
// avoiding the properties listed in "nulls"
BeanUtils.copyProperties(newModel, model, nulls);
modelRespository.save(model);
}).orElseThrow(() -> MyNotFoundException());
}
public static String[] getNullPropertyNames(Object source) {
final BeanWrapper wrappedSource = new BeanWrapperImpl(source);
return Stream.of(wrappedSource.getPropertyDescriptors())
.map(FeatureDescriptor::getName)
.filter(propertyName -> wrappedSource.getPropertyValue(propertyName) == null)
.toArray(String[]::new);
}

最新更新