Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can MapStruct be told to not perform automatic mappings?

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?

like image 780
pesche Avatar asked Jan 06 '16 09:01

pesche


People also ask

How do I ignore mapping 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 I map a MapStruct collection?

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.

Does MapStruct work with Java 11?

Yes, it works on a Java 11 / Spring Boot 2 project at work, and we use Mapstruct without issues.

How does MapStruct work in spring boot?

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.


2 Answers

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.

like image 66
oak Avatar answered Sep 29 '22 14:09

oak


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.

like image 29
Gunnar Avatar answered Sep 29 '22 14:09

Gunnar