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

Java 除了在spring boot中执行空检查之外,还有更有效的方法来处理补丁请求更新吗?,java,spring,spring-boot,spring-mvc,Java,Spring,Spring Boot,Spring Mvc,除了最初执行空检查,还有更好的更新方法吗 @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(new

除了最初执行空检查,还有更好的更新方法吗

@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框架添加要忽略的属性(在本例中为空属性),如下所示:

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

您可以在模型类中添加
@NotNull
。这个答案很有帮助