Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 838
Daniel Taub Avatar asked Jan 29 '18 20:01

Daniel Taub


People also ask

How do I ignore source field in MapStruct?

To do this, we use the MapStruct unmappedTargetPolicy to provide our desired behavior when there is no source field for the mapping: ERROR: any unmapped target property will fail the build – this can help us avoid accidentally unmapped fields. WARN: (default) warning messages during the build. IGNORE: no output or ...

How do I map a MapStruct list?

Using Mapstruct we can map list in similar fashion as we map primitives. To get a list of objects, we should provide a mapper method which can map an object.

What is MappingTarget in MapStruct?

Annotation Type MappingTargetDeclares a parameter of a mapping method to be the target of the mapping. Not more than one parameter can be declared as MappingTarget . NOTE: The parameter passed as a mapping target must not be null .

Does MapStruct work with Lombok?

Yes, as of MapStruct 1.2. 0. Beta1 and Lombok 1.16.


1 Answers

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

like image 157
Filip Avatar answered Sep 18 '22 20:09

Filip