我的映射器看起来像,
@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。
答案 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);
}