簡體   English   中英

除了在 spring 引導中執行空檢查之外,還有更有效的方法來處理補丁請求更新嗎?

[英]Is there a more efficient way to handle patch request updates other than performing null-checks in spring boot?

除了最初執行空檢查之外,還有更好的更新方法嗎?

@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添加要忽略的屬性(在這種情況下是 null ),如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM