如何使用mapstruct或modelmapper从一个对象递归更新嵌套对象?

时间:2018-12-26 23:55:20

标签: java mapstruct modelmapper

我最好通过一个我想要得到的例子来说明我的任务。 使用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
             }
}

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

1 个答案:

答案 0 :(得分:1)

是的,您可以使用MapStruct中的Updating existing bean instances进行所需的更新。

映射器如下所示:

currUser.getIdToken(true).then()

为此生成的代码如下:

@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() ); } } } -当源bean属性为nullValuePropertyMappingStrategy或不存在时要应用的策略。默认值为将目标值设置为null
  • null-确定何时包括对bean映射的源属性值的nullValueCheckStrategy检查

NB null来自MapStruct 1.3.0.Beta2