spring-data-jpa 简化补丁程序

w41d8nur  于 2022-11-10  发布在  Spring
关注(0)|答案(1)|浏览(146)

我必须修补我的实体来更新一些选择的字段。
我编写了下面的代码,有效负载中的用户可以键入他想要更新的字段,但不必像PUT那样更新所有字段:

public ResponseItemDTO patch(Long id, RequestAtualizaItemDTO requestItemDTO) {
        Item item = repositoryItem.findById(id)
                .orElseThrow(PedidoNaoEncontradoException::new);

        if(requestItemDTO.getName() != null) {
            item.setName(requestItemDTO.getName());
        }
        if(requestItemDTO.getValor() != null) {
            item.setValor(requestItemDTO.getValor());
        }
        if(requestItemDTO.getDesc() != null) {
            item.setDesc(requestItemDTO.getDesc());
        }
        if(requestItemDTO.getOffer() != null) {
            item.setOffer(requestItemDTO.getOffer());
        }
        repositoryItem.save(item);
        return modelMapper.map(item, ResponseItemDTO.class);
    }

我的问题是,是否有一个更简单的方法,使补丁,而不需要如果?

7lrncoxx

7lrncoxx1#

是的,我明白你的意思。我过去在一些项目中的方法是创建一个可重用的“补丁程序实用程序”,并将if/else-ing隐藏在其他地方....,.如果需要,它使用函数消费者来应用更改。
下面是一个包含两种类型的示例;您可以根据需要添加对类型的支持。

public final class Patcher {

    public static void patchInt(Integer value, IntConsumer consumer) {
        if (value != null) {
            consumer.accept(value);
        }
    }

    public static void patchString(String value, Consumer<String> consumer) {
        if (value != null) {
            consumer.accept(orNull(value));
        }
    }

    /* I'm using apache commons lang StringUtils but use whatever you want**/
    public static String orNull(String value) {
        if (StringUtils.isBlank(value)) {
            return null;
        }
        return value;
    }

}

然后,您可以这样使用它。

Patcher.patchInt(requestBody.intValue(), dbEntity::setIntValue);
Patcher.patchString(requestBody.stringValue(), dbEntity::setStringValue);

相关问题