Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MapStruct ignore automatically unmapped properties

Tags:

java

mapstruct

I am using MapStruct with big models (more than 50 fields) shared between different business use cases in my code. Depending on the entry point, some properties will be mapped and some not. When I build my project, I will always get the "WARNING: Unmapped target properties" message.

I have researched and seen that it is possible to tell the mapstruct to ignore the field by using the semantic

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

The problem is, given my objects with so many fields, it would take a lot of code to ignore each single property in each mapper class. I also do not want this Warning on my log. Is there any way to tell mapstruct to ignore what is not mapped, avoiding this message?

like image 809
Santiago Perez Chavez Avatar asked Apr 22 '16 08:04

Santiago Perez Chavez


People also ask

How do I ignore unmapped properties in MapStruct?

We can ignore unmapped properties in several mappers by setting the unmappedTargetPolicy via @MapperConfig to share a setting across several mappers. We should note that this is a simple example showing the minimal usage of @MapperConfig, which might not seem much better than setting the policy on each mapper.

How do you ignore fields in Mapper?

To do so we need to use the Ignore Property with the Address property of the destination type while doing the mapper configuration as shown below in the below image. As you can see in the above example, we have added the ForMember method to ignore the Address property while doing the mapping.

How do I set default value in MapStruct?

Syntax. default-value − target-property will be set as default-value in case source-property is null.

Does MapStruct use reflection?

During compilation, MapStruct will generate an implementation of this interface. This implementation uses plain Java method invocations for mapping between source and target objects, i.e. no reflection or similar.


2 Answers

You can set the "unmapped target policy" on the @Mapper level or via @MapperConfig to share a setting across several mappers:

@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface MyMapper {}
like image 179
Gunnar Avatar answered Oct 19 '22 09:10

Gunnar


For ignore automapping MapStruct 1.3.0.Final Reference Guide:

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.

@BeanMapping(ignoreByDefault = true)
OneObj map(TwoObj two);
like image 21
Safargaleev Ruslan Avatar answered Oct 19 '22 10:10

Safargaleev Ruslan