exclude specific fields in mapstruct

Daniel Taub picture Daniel Taub · Jan 29, 2018 · Viewed 12.7k times · Source

While I am trying to create a mapper between two classes in mapstruct,
I am getting a warning when I compile my code :

src/main/java/mapstruct/DogMapper.java:15: warning: Unmapped target property: "otherField".
    Cat convert(Dog dog);
        ^
1 warning

This are the two objects I am trying to map between :

Dog

@Getter
@Setter
public class Dog {
    private String say;
}

Cat

@Getter
@Setter
public class Cat {
    private String say;
    private String otherField;
}

And this is my Mapper

@Mapper
public interface DogMapper {
    DogMapper mapper = Mappers.getMapper( DogMapper.class );

    @Mapping(source = "say", target = "say")
    Cat convert(Dog dog);
}

I read the mapstruct docs, and I know i can exclude this specific field in many ways :

@Mapping(ignore = true, target = "otherField")

Or by this way :

@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE)

But my purpose in the end is to exclude the specific field called otherField,
from all my mappers, but not to exclude other field that I am not using.

Is there any way to achieve that?

Answer

Filip picture Filip · Jan 29, 2018

You have answered your own question, and I am not sure if I understood you correctly. You want to type @Mapping(ignore = true, target = "otherField") only once?

If this field is in some common base class you can use Shared Configurations. Otherwise the way you are doing with @Mapping(ignore = true) is the way to go.

One side note. You don't have to add @Mapping(source = "say", target = "say") MapStruct automatically maps properties with the same name