如何使用MapStruct实现部分自定义映射?

Tim*_*Tim 3 java mapstruct

我希望 MapStruct 映射我的 Object 的每个属性,除了我想为其提供自定义映射的一个特定属性

到目前为止,我自己实现了整个映射器,但是每次我向实体添加新属性时,我都会忘记更新映射器。

@Mapper(componentModel = "cdi")
public interface MyMapper {
    MyMapper INSTANCE = Mappers.getMapper(MyMapper.class);

    default MyDto toDTO(MyEntity myEntity){
        MyDto dto = new MyDto();
        dto.field1 = myEntity.field1;
        // [...]
        dto.fieldN = myEntity.fieldN;

        // Custom mapping here resulting in a Map<> map
        dto.fieldRequiringCustomMapping = map;

    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法将我的字段 fieldRequiringCustomMapping 的映射外包并告诉 MapStruct 像往常一样映射所有其他字段

Fil*_*lip 6

MapStruct 有一种在某些字段之间使用自定义映射的方法。因此,根据您的情况,您可以执行以下操作:

@Mapper(componentModel = "cdi")
public interface MyMapper {

    @Mapping(target = "fieldRequiringCustomMapping", qualifiedByName = "customFieldMapping")
    MyDto toDTO(MyEntity myEntity);

    // The @(org.mapstruct.)Named is only needed if the Return and Target type are not unique
    @Named("customFieldMapping")
    default FieldRequiringCustomMapping customMapping(SourceForFieldRequiringCustomMapping source) {
        // Custom mapping here resulting in a Map<> map
        return map
    }
    
}
Run Code Online (Sandbox Code Playgroud)

我不知道您fieldRequiringCustomMapping需要映射什么,该示例假设您也有这样的字段MyEntity,如果不是这种情况,您需要添加source@Mapping.


附注:componentModel在您的情况下使用非默认值时cdi,不建议使用Mappers工厂。如果您在映射器中使用其他映射器,它不会执行其他映射器的注入。