【问题标题】:How recursively update nested objects from one object by another use mapstruct or modelmapper?如何通过另一个使用 mapstruct 或 modelmapper 从一个对象递归更新嵌套对象?
【发布时间】:2018-12-26 23:55:19
【问题描述】:

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

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

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

【问题讨论】:

    标签: java mapstruct modelmapper


    【解决方案1】:

    是的,您可以使用 MapStruct 中的 Updating existing bean instances 来执行您正在寻找的更新。

    映射器看起来像:

    @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 - 确定何时对 bean 映射的源属性值进行 null 检查

    NBnullValuePropertyMappingStrategy 来自 MapStruct 1.3.0.Beta2

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-28
      • 2021-11-17
      • 2012-04-05
      • 1970-01-01
      • 2020-06-27
      • 1970-01-01
      相关资源
      最近更新 更多