【问题标题】:Mapstruct - mapper object needs valuemapping of an object fieldMapstruct - 映射器对象需要对象字段的值映射
【发布时间】:2025-11-27 21:00:01
【问题描述】:

我有一个对象A,我正在尝试将其映射到B。现在这个A 有一个名为field1 的枚举,其中包含一些值。我想使用@ValueMappings 将它们映射到B 中的其他枚举值。以下是我到目前为止的代码:

@Mapping(source = "field1", target = "field1", nullValuePropertyMappingStrategy = IGNORE)
@Mapping(source = "field2", target = "field2", nullValuePropertyMappingStrategy = IGNORE)
@ValueMappings({
    @ValueMapping(source = "field1.some1", target = "diff1"),
    @ValueMapping(source = "field1.some2", target = "diff1"),
    @ValueMapping(source = "field1.some3", target = "diff1"),
    @ValueMapping(source = "field1.some4", target = "diff2"),
})
B map(A a);

当我尝试编译它时,我得到了错误:

error: The following constants from the property "A.field1 field1" enum have no corresponding constant in the "B field1" enum and must be be mapped via adding additional mappings: diff1, diff2.

【问题讨论】:

    标签: mapstruct


    【解决方案1】:

    解决此问题的一种方法是执行以下操作:

    @Mapper(componentModel = "spring",  uses = {SomeUtil.class}, unmappedTargetPolicy = ReportingPolicy.IGNORE)
    public interface Mapper {
        @Mapping(source = "field1", target = "field1", nullValuePropertyMappingStrategy = IGNORE)
        @Mapping(source = "field2", target = "field2", nullValuePropertyMappingStrategy = IGNORE)
        B map(A a);
    }
    

    在 SomeUtil.class 中:

    @Mapper(componentModel = "spring")
    public interface SomeUtil {
    
        @ValueMappings({
            @ValueMapping(source = "field1.some1", target = "diff1"),
            @ValueMapping(source = "field1.some2", target = "diff1"),
            @ValueMapping(source = "field1.some3", target = "diff1"),
            @ValueMapping(source = "field1.some4", target = "diff2"),
        })
        b.field1 map(a.field1 field);
    }
    

    【讨论】: