首页 > 解决方案 > 如何使用 mapstruct 或 modelmapper 从一个对象递归更新嵌套对象?

问题描述

最好我通过一个我想要得到的例子来解释我的任务。是否可以使用 mapstruct / modelmapper / 等来解决这个问题?

class Person{
    String name;
    Address address;
}

class Address{
    String street;
    Integer home;
}

更新:

{
    name: "Bob"
    address: {
                 street: "Abbey Road"
             }
}

目标:

{
    name: "Michael"
    address: {
                 street: "Kitano"
                 home: 5
             }
}

结果我想得到:

{
    name: "Bob"
    address: {
                 street: "Abbey Road"
                 home: 5
             }
}

它不能重写地址对象。它递归地在其中设置新值。

标签: javamapstructmodelmapper

解决方案


是的,您可以使用从 MapStruct更新现有 bean 实例来执行您正在寻找的更新。

映射器看起来像:

@Mapper(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE, nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS)
public interface PersonMapper {

    void update(@MappingTarget Person toUpdate, Person person);

    void update(@MappingTarget Address toUpdate, Address address);
}

为此生成的代码如下所示:

public class PersonMapperImpl implements PersonMapper {

    @Override
    public void update(Person toUpdate, Person person) {
        if ( person == null ) {
            return;
        }

        if ( person.getName() != null ) {
            toUpdate.setName( person.getName() );
        }
        if ( person.getAddress() != null ) {
            if ( toUpdate.getAddress() == null ) {
                toUpdate.setAddress( new Address() );
            }
            update( toUpdate.getAddress(), person.getAddress() );
        }
    }

    @Override
    public void update(Address toUpdate, Address address) {
        if ( address == null ) {
            return;
        }

        if ( address.getStreet() != null ) {
            toUpdate.setStreet( address.getStreet() );
        }
        if ( address.getHome() != null ) {
            toUpdate.setHome( address.getHome() );
        }
    }
}
  • nullValuePropertyMappingStrategy- 当源 bean 属性存在null或不存在时应用的策略。默认是将值设置为目标值null
  • nullValueCheckStrategy- 确定何时包括null对 bean 映射的源属性值的检查

注意来自nullValuePropertyMappingStrategyMapStruct 1.3.0.Beta2


推荐阅读