Java – How can I prevent mapstruct from mapping a large number of fields without having to manually exclude them?

How can I prevent mapstruct from mapping a large number of fields without having to manually exclude them?… here is a solution to the problem.

How can I prevent mapstruct from mapping a large number of fields without having to manually exclude them?

I’m using mapstruct to map objects to DTOs. My object has 100 fields that need to be mapped into DTOs, and about 30 fields that should not be mapped.

How to ignore these 30 fields without writing 30 times

@Mapping(source = "fieldtoIgnore", ignore = true)

I

don’t want to ignore the warning, I want to prevent mapstruct from mapping certain fields entirely

Thanks

Solution

You can define the following annotations on the mapping method:

@BeanMapping(ignoreByDefault = true)

This causes Mapstruct to ignore all matching fields between the two classes by default.

This is a quote from this comment in the Mapstruct documentation:

By means of the @BeanMapping(ignoreByDefault = true) the default
behavior will be explicit mapping, meaning that all mappings have to
be specified by means of the @Mapping and no warnings will be issued
on missing target properties.

And link to javadoc:
http://mapstruct.org/documentation/stable/api/org/mapstruct/BeanMapping.html

Related Problems and Solutions