Mapstruct-映射器对象需要对对象字段进行值映射

问题描述 投票:0回答:1

我有一个要映射到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个回答
0
投票

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

@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);
}
© www.soinside.com 2019 - 2024. All rights reserved.