使用 MapStruct 的嵌套映射

Nested Mapping using MapStruct

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);

}

到此为止一切正常。现在我想将 custStatusesCustomerProfileDO class 的 category 映射到 Identifier class 的 statusestype .我不知道如何将 CustomerProfileDO 对象提供给 toIdentifier 映射方法,以便我可以在其中包含映射本身。我尝试关注

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

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

toIdentifer(CustomerIdentifierDO identifierDO)

有什么办法可以实现吗?

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

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

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