I have a rather big bean (~ 100 properties) that is mapped into several smaller objects. It may occur that the smaller target objects have properties with the same name as in my source bean, but not with the same semantic meaning.
I would like MapStruct to behave in this specific case to map only what I explicitly tell using a @Mapping
annotation and not perform the usual automatic mapping.
The MapStruct documentation tells me just this:
In the generated method implementations all readable properties from the source type (...) will be copied into the corresponding property in the target type (...).
I didn't find any configuration option switching this behavior off. Can it be done?
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.
In general, mapping collections with MapStruct works the same way as for simple types. Basically, we have to create a simple interface or abstract class, and declare the mapping methods. Based on our declarations, MapStruct will generate the mapping code automatically.
Yes, it works on a Java 11 / Spring Boot 2 project at work, and we use Mapstruct without issues.
Mapstruct is an annotation-based code generator that simplifies the mapping implementations between the java beans. The code is generated via the plain method invocation and thus it is fast, type-safe, and easy to understand.
Switching off implicit field mapping is possible via @BeanMapping(ignoreByDefault = true)
mapping method annotation since MapStruct 1.3. From MapStruct 1.3.1 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.
As stated in Mohamed's comment, you could ignore these properties explicitly.
There is no switch as you describe it. Personally I'd probably write that specific mapping from hand instead of explicitly configuring all the mappings through annotations. Granted, you'd still benefit from type conversion etc., so it may still be beneficial, it really depends on your use case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With