【问题标题】:Mapstruct - mapper object needs valuemapping of an object fieldMapstruct - 映射器对象需要对象字段的值映射
【发布时间】:2020-05-09 07:06:26
【问题描述】:

我有一个对象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);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-02-17
      • 1970-01-01
      • 2016-12-04
      • 1970-01-01
      • 2021-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多