0
# Core Mapping
1
2
Core mapping functionality that forms the foundation of MapStruct's mapping capabilities. These annotations define mappers and configure individual property mappings with extensive customization options.
3
4
## Capabilities
5
6
### Mapper Interface Definition
7
8
Marks an interface or abstract class as a mapper, activating MapStruct's code generation process.
9
10
```java { .api }
11
/**
12
* Marks an interface or abstract class as a mapper and activates the generation of a implementation of that type via MapStruct.
13
*/
14
@Target(ElementType.TYPE)
15
@Retention(RetentionPolicy.CLASS)
16
@interface Mapper {
17
/** Other mapper types used by this mapper */
18
Class<?>[] uses() default {};
19
20
/** Additional types for import statements in generated mapper */
21
Class<?>[] imports() default {};
22
23
/** How unmapped properties of the source type should be reported */
24
ReportingPolicy unmappedSourcePolicy() default ReportingPolicy.IGNORE;
25
26
/** How unmapped properties of the target type should be reported */
27
ReportingPolicy unmappedTargetPolicy() default ReportingPolicy.WARN;
28
29
/** How lossy (narrowing) conversion should be reported */
30
ReportingPolicy typeConversionPolicy() default ReportingPolicy.IGNORE;
31
32
/** Specifies the component model for the generated mapper */
33
String componentModel() default "default";
34
35
/** Specifies the name of the implementation class */
36
String implementationName() default "<CLASS_NAME>Impl";
37
38
/** Specifies the target package for the generated implementation */
39
String implementationPackage() default "<PACKAGE_NAME>";
40
41
/** Class annotated with @MapperConfig to use as configuration template */
42
Class<?> config() default void.class;
43
44
/** Strategy for propagating collection-typed properties */
45
CollectionMappingStrategy collectionMappingStrategy() default CollectionMappingStrategy.ACCESSOR_ONLY;
46
47
/** Strategy when null is passed as source argument */
48
NullValueMappingStrategy nullValueMappingStrategy() default NullValueMappingStrategy.RETURN_NULL;
49
50
/** Strategy when null is passed as source argument to IterableMapping */
51
NullValueMappingStrategy nullValueIterableMappingStrategy() default NullValueMappingStrategy.RETURN_NULL;
52
53
/** Strategy when null is passed as source argument to MapMapping */
54
NullValueMappingStrategy nullValueMapMappingStrategy() default NullValueMappingStrategy.RETURN_NULL;
55
56
/** Strategy when source bean property is null or not present */
57
NullValuePropertyMappingStrategy nullValuePropertyMappingStrategy() default NullValuePropertyMappingStrategy.SET_TO_NULL;
58
59
/** Strategy for applying method-level configuration annotations */
60
MappingInheritanceStrategy mappingInheritanceStrategy() default MappingInheritanceStrategy.EXPLICIT;
61
62
/** When to include null check on source property value */
63
NullValueCheckStrategy nullValueCheckStrategy() default NullValueCheckStrategy.ON_IMPLICIT_CONVERSION;
64
65
/** How to handle missing implementation for super classes when using SubclassMapping */
66
SubclassExhaustiveStrategy subclassExhaustiveStrategy() default SubclassExhaustiveStrategy.COMPILE_ERROR;
67
68
/** Determines whether to use field or constructor injection */
69
InjectionStrategy injectionStrategy() default InjectionStrategy.FIELD;
70
71
/** Whether to disable automatic generation of sub-mapping methods */
72
boolean disableSubMappingMethodsGeneration() default false;
73
74
/** Builder configuration information */
75
Builder builder() default @Builder;
76
77
/** Allows detailed control over the mapping process */
78
Class<? extends Annotation> mappingControl() default MappingControl.class;
79
80
/** Exception to throw for unmapped enum values */
81
Class<? extends Exception> unexpectedValueMappingException() default IllegalArgumentException.class;
82
83
/** Whether to suppress timestamp in @Generated annotation */
84
boolean suppressTimestampInGenerated() default false;
85
}
86
```
87
88
**Usage Examples:**
89
90
```java
91
// Basic mapper
92
@Mapper
93
public interface CarMapper {
94
CarMapper INSTANCE = Mappers.getMapper(CarMapper.class);
95
96
CarDto toCarDto(Car car);
97
}
98
99
// Mapper with Spring integration
100
@Mapper(componentModel = "spring")
101
public interface UserMapper {
102
@Mapping(source = "fullName", target = "name")
103
UserDto toUserDto(User user);
104
}
105
106
// Mapper with custom configuration
107
@Mapper(
108
uses = DateMapper.class,
109
unmappedTargetPolicy = ReportingPolicy.ERROR,
110
nullValueMappingStrategy = NullValueMappingStrategy.RETURN_DEFAULT
111
)
112
public interface OrderMapper {
113
OrderDto toOrderDto(Order order);
114
}
115
```
116
117
### Property Mapping Configuration
118
119
Configures the mapping of individual bean attributes with extensive customization options.
120
121
```java { .api }
122
/**
123
* Configures the mapping of one bean attribute.
124
*/
125
@Repeatable(Mappings.class)
126
@Retention(RetentionPolicy.CLASS)
127
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
128
@interface Mapping {
129
/** The target name of the configured property */
130
String target();
131
132
/** The source name of the configured property */
133
String source() default "";
134
135
/** Date format string for Date to String conversion */
136
String dateFormat() default "";
137
138
/** Number format string for Number to String conversion */
139
String numberFormat() default "";
140
141
/** Constant String value to set target property to */
142
String constant() default "";
143
144
/** Java expression to compute target property value */
145
String expression() default "";
146
147
/** Default expression if source property is null */
148
String defaultExpression() default "";
149
150
/** Whether the target property should be ignored */
151
boolean ignore() default false;
152
153
/** Qualifiers for mapper method selection */
154
Class<? extends Annotation>[] qualifiedBy() default {};
155
156
/** String-based qualifiers for mapper method selection */
157
String[] qualifiedByName() default {};
158
159
/** Qualifiers for condition method selection */
160
Class<? extends Annotation>[] conditionQualifiedBy() default {};
161
162
/** String-based qualifiers for condition method selection */
163
String[] conditionQualifiedByName() default {};
164
165
/** Condition expression for property mapping */
166
String conditionExpression() default "";
167
168
/** Result type for mapping method selection */
169
Class<?> resultType() default void.class;
170
171
/** Properties on which this mapped property depends */
172
String[] dependsOn() default {};
173
174
/** Default value if source property is null */
175
String defaultValue() default "";
176
177
/** When to include null check on source property */
178
NullValueCheckStrategy nullValueCheckStrategy() default NullValueCheckStrategy.ON_IMPLICIT_CONVERSION;
179
180
/** Strategy when source property is null or not present */
181
NullValuePropertyMappingStrategy nullValuePropertyMappingStrategy() default NullValuePropertyMappingStrategy.SET_TO_NULL;
182
183
/** Allows detailed control over the mapping process */
184
Class<? extends Annotation> mappingControl() default MappingControl.class;
185
}
186
```
187
188
**Usage Examples:**
189
190
```java
191
@Mapper
192
public interface PersonMapper {
193
// Basic property mapping
194
@Mapping(source = "firstName", target = "name")
195
PersonDto toPersonDto(Person person);
196
197
// Multiple mappings with different strategies
198
@Mapping(source = "birthDate", target = "dateOfBirth", dateFormat = "yyyy-MM-dd")
199
@Mapping(source = "salary", target = "income", numberFormat = "#,###.00")
200
@Mapping(target = "status", constant = "ACTIVE")
201
@Mapping(target = "id", ignore = true)
202
PersonDto toDetailedPersonDto(Person person);
203
204
// Expression-based mapping
205
@Mapping(target = "fullName", expression = "java(person.getFirstName() + \" \" + person.getLastName())")
206
@Mapping(target = "age", expression = "java(java.time.Period.between(person.getBirthDate(), java.time.LocalDate.now()).getYears())")
207
PersonSummaryDto toPersonSummaryDto(Person person);
208
209
// Conditional mapping
210
@Mapping(target = "email", conditionExpression = "java(person.getEmail() != null && person.getEmail().contains(\"@\"))")
211
ContactDto toContactDto(Person person);
212
213
// Default values
214
@Mapping(source = "nickname", target = "displayName", defaultValue = "Unknown")
215
@Mapping(source = "country", target = "location", defaultExpression = "java(\"Unknown Location\")")
216
DisplayDto toDisplayDto(Person person);
217
}
218
```
219
220
### Bean Mapping Configuration
221
222
Configures mapping between bean types at the method level.
223
224
```java { .api }
225
/**
226
* Configures the mapping between two bean types.
227
*/
228
@Target(ElementType.METHOD)
229
@Retention(RetentionPolicy.CLASS)
230
@interface BeanMapping {
231
/** Result type to select in case multiple mapping methods qualify */
232
Class<?> resultType() default void.class;
233
234
/** Qualifiers for factory method selection */
235
Class<? extends Annotation>[] qualifiedBy() default {};
236
237
/** String-based qualifiers for factory method selection */
238
String[] qualifiedByName() default {};
239
240
/** Strategy when null is passed as source argument */
241
NullValueMappingStrategy nullValueMappingStrategy() default NullValueMappingStrategy.RETURN_NULL;
242
243
/** Strategy when source bean property is null or not present */
244
NullValuePropertyMappingStrategy nullValuePropertyMappingStrategy() default NullValuePropertyMappingStrategy.SET_TO_NULL;
245
246
/** When to include null check on source property value */
247
NullValueCheckStrategy nullValueCheckStrategy() default NullValueCheckStrategy.ON_IMPLICIT_CONVERSION;
248
249
/** Whether to ignore all mappings by default */
250
boolean ignoreByDefault() default false;
251
252
/** Unmapped source properties to ignore in reporting */
253
String[] ignoreUnmappedSourceProperties() default {};
254
255
/** Builder configuration for this mapping */
256
Builder builder() default @Builder;
257
258
/** Allows detailed control over the mapping process */
259
Class<? extends Annotation> mappingControl() default MappingControl.class;
260
261
/** How to handle missing implementation for super classes */
262
SubclassExhaustiveStrategy subclassExhaustiveStrategy() default SubclassExhaustiveStrategy.COMPILE_ERROR;
263
}
264
```
265
266
**Usage Examples:**
267
268
```java
269
@Mapper
270
public interface OrderMapper {
271
// Bean mapping with null value strategy
272
@BeanMapping(nullValueMappingStrategy = NullValueMappingStrategy.RETURN_DEFAULT)
273
OrderDto toOrderDto(Order order);
274
275
// Ignore unmapped properties by default
276
@BeanMapping(ignoreByDefault = true)
277
@Mapping(target = "id", source = "orderId")
278
@Mapping(target = "total", source = "amount")
279
SimpleOrderDto toSimpleOrderDto(Order order);
280
281
// Ignore specific unmapped source properties
282
@BeanMapping(ignoreUnmappedSourceProperties = {"internalNotes", "auditInfo"})
283
PublicOrderDto toPublicOrderDto(Order order);
284
}
285
```
286
287
### Multiple Mappings Container
288
289
Container annotation for multiple @Mapping annotations (pre-Java 8 compatibility).
290
291
```java { .api }
292
/**
293
* Is used to hold multiple @Mapping annotations as Java 8 introduces repeating annotations.
294
*/
295
@Target(ElementType.METHOD)
296
@Retention(RetentionPolicy.CLASS)
297
@interface Mappings {
298
/** The mapping configurations */
299
Mapping[] value();
300
}
301
```
302
303
**Usage Example:**
304
305
```java
306
@Mapper
307
public interface LegacyMapper {
308
// Pre-Java 8 style multiple mappings
309
@Mappings({
310
@Mapping(source = "firstName", target = "name"),
311
@Mapping(source = "birthDate", target = "dateOfBirth", dateFormat = "yyyy-MM-dd"),
312
@Mapping(target = "id", ignore = true)
313
})
314
PersonDto toPersonDto(Person person);
315
}
316
```
317
318
### Mapper Configuration Template
319
320
Shared configuration template for multiple mappers.
321
322
```java { .api }
323
/**
324
* Marks a class or interface as configuration source for generated mappers.
325
*/
326
@Target(ElementType.TYPE)
327
@Retention(RetentionPolicy.CLASS)
328
@interface MapperConfig {
329
/** Other mapper types used by mappers using this configuration */
330
Class<?>[] uses() default {};
331
332
/** Additional types for import statements */
333
Class<?>[] imports() default {};
334
335
/** How unmapped properties of the source type should be reported */
336
ReportingPolicy unmappedSourcePolicy() default ReportingPolicy.IGNORE;
337
338
/** How unmapped properties of the target type should be reported */
339
ReportingPolicy unmappedTargetPolicy() default ReportingPolicy.WARN;
340
341
/** How lossy conversion should be reported */
342
ReportingPolicy typeConversionPolicy() default ReportingPolicy.IGNORE;
343
344
/** Component model for generated mappers */
345
String componentModel() default "default";
346
347
/** Name of implementation class */
348
String implementationName() default "<CLASS_NAME>Impl";
349
350
/** Target package for generated implementation */
351
String implementationPackage() default "<PACKAGE_NAME>";
352
353
/** Strategy for collection-typed properties */
354
CollectionMappingStrategy collectionMappingStrategy() default CollectionMappingStrategy.ACCESSOR_ONLY;
355
356
/** Strategy when null is passed as source argument */
357
NullValueMappingStrategy nullValueMappingStrategy() default NullValueMappingStrategy.RETURN_NULL;
358
359
/** Strategy when null is passed to IterableMapping */
360
NullValueMappingStrategy nullValueIterableMappingStrategy() default NullValueMappingStrategy.RETURN_NULL;
361
362
/** Strategy when null is passed to MapMapping */
363
NullValueMappingStrategy nullValueMapMappingStrategy() default NullValueMappingStrategy.RETURN_NULL;
364
365
/** Strategy when source bean property is null or not present */
366
NullValuePropertyMappingStrategy nullValuePropertyMappingStrategy() default NullValuePropertyMappingStrategy.SET_TO_NULL;
367
368
/** Strategy for applying method-level configuration annotations */
369
MappingInheritanceStrategy mappingInheritanceStrategy() default MappingInheritanceStrategy.EXPLICIT;
370
371
/** When to include null check on source property value */
372
NullValueCheckStrategy nullValueCheckStrategy() default NullValueCheckStrategy.ON_IMPLICIT_CONVERSION;
373
374
/** How to handle missing implementation for super classes */
375
SubclassExhaustiveStrategy subclassExhaustiveStrategy() default SubclassExhaustiveStrategy.COMPILE_ERROR;
376
377
/** Whether to use field or constructor injection */
378
InjectionStrategy injectionStrategy() default InjectionStrategy.FIELD;
379
380
/** Whether to disable automatic generation of sub-mapping methods */
381
boolean disableSubMappingMethodsGeneration() default false;
382
383
/** Builder configuration */
384
Builder builder() default @Builder;
385
386
/** Exception to throw for unmapped enum values */
387
Class<? extends Exception> unexpectedValueMappingException() default IllegalArgumentException.class;
388
389
/** Whether to suppress timestamp in @Generated annotation */
390
boolean suppressTimestampInGenerated() default false;
391
}
392
```
393
394
**Usage Example:**
395
396
```java
397
// Shared configuration
398
@MapperConfig(
399
componentModel = "spring",
400
unmappedTargetPolicy = ReportingPolicy.ERROR,
401
uses = {DateMapper.class, StringMapper.class}
402
)
403
public interface CentralConfig {
404
}
405
406
// Mappers using the configuration
407
@Mapper(config = CentralConfig.class)
408
public interface UserMapper {
409
UserDto toUserDto(User user);
410
}
411
412
@Mapper(config = CentralConfig.class)
413
public interface OrderMapper {
414
OrderDto toOrderDto(Order order);
415
}
416
```