Mapstructs在MapperImpl中生成错误的代码

时间:2018-06-05 08:42:34

标签: java mapstruct

我的映射器看起来像,

@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE)
public abstract class PersonMapper
{
    @Mapping(target = "someModel", source = "someEto")
    @Mapping(target = "someModel.bloodGroup", source = "someOtherEto.bloodGroup")
    @Mapping(target = "someModel.nature", source = "someOtherEto.nature")
    public abstract PersonModel mapPersonCtoToPersonModel(PersonCto personCto);
}

生成以下Impl

@Override
public PersonModel mapPersonCtoToPersonModel(PersonCto personCto) {
    if ( personCto == null ) {
        return null;
    }

    PersonModel personModel = new PersonModel();

    personModel.setSomeModel( someOtherEtoToSomeModel( personCto.getSomeOtherEto() ) );
    personModel.setSomeModel( someEtoToSomeModel( personCto.getSomeEto() ) );

    return personModel;
}

但是,设置someModel两次将替换已设置的模型。这是Mapstruct的正常行为吗? 除了AfterMapping之外,我能做些什么才能使这个工作?因为我有足够大且复杂的嵌套模型和Etos。

1 个答案:

答案 0 :(得分:0)

您应该为每个嵌套类创建映射器(代码未经测试):

@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE)
public abstract class SomeModelMapper {     
    public abstract SomeModel map(SomeEto someEto);
}

@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE, uses = { SomeModelMapper.class })
public abstract class PersonMapper {
    @Mapping(target = "someModel", source = "someEto")
    public abstract PersonModel map(PersonCto personCto);
}

或者您也可以按照自己的方式进行操作,但需要删除第一个@Mapping

@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE)
public abstract class PersonMapper {
    // @Mapping(target = "someModel", source = "someEto")
    @Mapping(target = "someModel.bloodGroup", source = "someOtherEto.bloodGroup")
    @Mapping(target = "someModel.nature", source = "someOtherEto.nature")
    public abstract PersonModel mapPersonCtoToPersonModel(PersonCto personCto);
}