使用MapStruct进行嵌套映射

时间:2018-04-05 17:49:31

标签: java mapstruct object-object-mapping

class Identifier {
    private long id;
    private String type;
    private List<Status> statuses;
}     

class Customer {
    private Identifier identifier;
}

class CustomerProfile {
    private Customer customer;
}

class CustomerIdentifierDO {
    private long id;
}

class CustomeDO {
    private CustomerIdentiferDO custID;

}

class CustomerProfileDO {
    private String category;
    private List<Status> custStatuses;
    private CustomeDO customer;
}

@Mapper
public interface CustomerProfileMapper {
    CustomerProfile toCustomerProfile(CustomerProfileDO profileDO) ;  
    Customer   toCustomer(CustomerDO customerDO);
    Identifier toIdentifier(CustomerIdentifierDO identifierDO);

}

一切正常,直到这个。现在,我想将custStatuses类的categoryCustomerProfileDO映射到statuses类的typeIdentifier。我不知道如何将CustomerProfileDO对象提供给toIdentifier映射方法,以便我可以在其中包含映射。我试过跟着

@Mappings({
     @Mapping(target = "customer.identifier.type", source = "category")
})
CustomerProfile   toCustomerProfile(CustomerProfileDO profileDO) ; 

但是这个嵌套映射覆盖了下面方法的所有映射配置。这不应该发生。

toIdentifer(CustomerIdentifierDO identifierDO)

有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:1)

目前,MapStruct可以将源参数传递给单个方法。为了实现您所寻找的目标(不使用嵌套目标类型,您需要使用@AfterMapping之类的东西。它看起来像:

@Mapper
public interface CustomerProfileMapper {
    CustomerProfile toCustomerProfile(CustomerProfileDO profileDO) ;  
    Customer   toCustomer(CustomerDO customerDO);
    Identifier toIdentifier(CustomerIdentifierDO identifierDO);


    default void afterMapping(@MappingTarget CustomerProfile profile, CustomerProfieDO profileDO) {
        Identifier identifier = profile.getCustomer().getIdentifier();
        identifier.setStatus(profileDO.setStatus());
        identifier.setType(profileDO.setCategory());
    }    
}