Mapstruct - mapper object needs valuemapping of an object field

Viewed 2959

I have an object A which I am trying to map to B. Now this A has an enum named field1 with some values. I want to map them using @ValueMappings to someother enum value in B. Below is my code till now:

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

When I try to compile this, I get the error:

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.
1 Answers

One way to solve this problem is to do something like this:

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

And in 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);
}
Related