Daniel Taub
Daniel Taub

Reputation: 5369

exclude specific fields in mapstruct

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?

Upvotes: 11

Views: 36322

Answers (2)

Bluexin
Bluexin

Reputation: 31

I know it might not answer the original question, but I can't answer the comment about repeating @Mapping annotation because I'm lacking reputation and I figured other people would land here looking for this.

You can totally combine annotations :

@Mapping(ignore = true, target = "version")
@Mapping(ignore = true, target = "created")
@Mapping(ignore = true, target = "updated")
fun toModel(json: JsonClass): ModelClass

If you have a set of fields you reuse commonly, you can also combine them by making your own annotations :

@Mapping(source = "version", ignore = true, target = "version")
@Mapping(source = "created", ignore = true, target = "created")
@Mapping(source = "updated", ignore = true, target = "updated")
annotation class ToModelMapping

Upvotes: 3

Filip
Filip

Reputation: 21393

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

Upvotes: 17

Related Questions