### Example 1: Creating mapper Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/Mapper.html Example 1: Creating a mapper. Marks an interface as a mapper and activates generation of its implementation. ```java @Mapper public interface CarMapper { CarDto toCarDto(Car source); } ``` -------------------------------- ### Example 2: Use additional mappers with uses(), componentModel(), injectionStrategy() Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/Mapper.html Example 2: Use additional mappers with parameters uses(), componentModel() and injectionStrategy(). Shows the mapper definitions and the generated implementation. ```java // we have MarkMapper (map field "mark" to field "name" to upper case) @Mapper(componentModel = MappingConstants.ComponentModel.SPRING) public class MarkMapper { public String mapMark(String mark) { return mark.toUpperCase(); } } // we have CarMapper @Mapper( componentModel = MappingConstants.ComponentModel.SPRING, uses = MarkMapper.class, injectionStrategy = InjectionStrategy.CONSTRUCTOR) public interface CarMapper { @Mapping(target = "name", source = "mark") CarDto convertMap(CarEntity carEntity); } ``` ```java // generates @Component public class CarMapperImpl implements CarMapper { private final MarkMapper markMapper; @Autowired public CarMapperImpl(MarkMapper markMapper) { this.markMapper = markMapper; } @Override public CarDto convertMap(CarEntity carEntity) { if ( carEntity == null ) { return null; } CarDto carDto = new CarDto(); carDto.setName( markMapper.mapMark( carEntity.getMark() ) ); return carDto; } } ``` -------------------------------- ### Example of @AfterMapping methods and generated mapping Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/AfterMapping.html This example shows three @AfterMapping methods with different parameter combinations and the generated mapping method that invokes them. The methods are called in the order they are defined, and the generated code shows the invocation of each method before the return statement. ```java @AfterMapping public void calledWithoutArgs() { // ... } @AfterMapping public void calledWithSourceAndTargetType(SourceEntity anySource, @TargetType Class targetType) { // ... } @AfterMapping public void calledWithSourceAndTarget(Object anySource, @MappingTarget TargetDto target) { // ... } public abstract TargetDto toTargetDto(SourceEntity source); // generates: public TargetDto toTargetDto(SourceEntity source) { if ( source == null ) { return null; } TargetDto targetDto = new TargetDto(); // actual mapping code calledWithoutArgs(); calledWithSourceAndTargetType( source, TargetDto.class ); calledWithSourceAndTarget( source, targetDto ); return targetDto; } ``` -------------------------------- ### Mapping method example Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/internal/model/beanmapping/TargetReference.html Shows a mapping method using @Mapping with target and source properties, illustrating how TargetReference is used. ```java @Mapping(target = "propC", source = "in.propA.propB") TypeB mappingMethod(TypeA in); ``` -------------------------------- ### Example of @BeforeMapping usage and generated mapping method Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/BeforeMapping.html Shows three @BeforeMapping methods and the generated mapping method that calls them. ```java @BeforeMapping public void calledWithoutArgs() { // ... } @BeforeMapping public void calledWithSourceAndTargetType(SourceEntity anySource, @TargetType Class targetType) { // ... } @BeforeMapping public void calledWithSourceAndTarget(Object anySource, @MappingTarget TargetDto target) { // ... } public abstract TargetDto toTargetDto(SourceEntity source); // generates: public TargetDto toTargetDto(SourceEntity source) { calledWithoutArgs(); calledWithSourceAndTargetType( source, TargetDto.class ); if ( source == null ) { return null; } TargetDto targetDto = new TargetDto(); calledWithSourceAndTarget( source, targetDto ); // actual mapping code return targetDto; } ``` -------------------------------- ### Expression attribute example Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/Mapping.html Shows how to use the expression attribute with the java() syntax to set a target property using a Java expression. The example maps a source property to a new TimeAndFormat instance. ```java @Mapping( target = "someProp", expression = "java(new TimeAndFormat( s.getTime(), s.getFormat() ))" ) ``` -------------------------------- ### Default expression example Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/Mapping.html Shows how to use the defaultExpression attribute with the java() syntax to set a target property when the source property is null. The example creates a new TimeAndFormat instance. ```java @Mapping( target = "someProp", defaultExpression = "java(new TimeAndFormat( s.getTime(), s.getFormat() ))" ) ``` -------------------------------- ### Example 2: Mapping properties with different names Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/Mapping.html Shows using @Mapping with source and target to map Human.companyName to HumanDto.company, and the generated implementation. ```java // We need map Human.companyName to HumanDto.company // we can use @Mapping with parameters source() and target() @Mapper public interface HumanMapper { @Mapping(source="companyName", target="company") HumanDto toHumanDto(Human human) } ``` ```java // generates: @Override public HumanDto toHumanDto(Human human) { humanDto.setCompany( human.getCompanyName() ); // ... } ``` -------------------------------- ### @ObjectFactory Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ObjectFactory.html Documentation for the @ObjectFactory annotation, including its declaration, usage notes, and an example. ```APIDOC ## @ObjectFactory ### Description Marks a method as a factory method to create beans during mapping. By default, beans are created with the default constructor; if a factory method with an assignable return type is present, it is used instead. Factory methods can be defined without parameters, with a @TargetType parameter, a @Context parameter, or with the mapping source parameter. ### Annotation Declaration ```java @Retention(CLASS) @Target(METHOD) public @interface ObjectFactory ``` ### Usage Notes - The annotation is optional when used in `Mapper.uses()` if no source parameters are part of the signature (i.e., declared without parameters or only with `@TargetType` and/or `@Context`). - The annotation is mandatory when used inside an `@Context` annotated class. - If two factory methods serve the same type, one with no parameters and one taking sources as input, the one with source parameters is favored. If multiple such factories exist, an ambiguity error is shown. ### Example ```java @ApplicationScoped // CDI component model public class ReferenceMapper { @PersistenceContext private EntityManager em; @ObjectFactory public T resolve(AbstractDto sourceDto, @TargetType Class type) { T entity = em.find( type, sourceDto.getId() ); return entity != null ? entity : type.newInstance(); } } ``` ### Since 1.2 ### Author Remo Meier ``` -------------------------------- ### Example 1: Implicit mapping of same-named properties Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/Mapping.html Shows a mapper interface where properties with the same name are mapped implicitly, and the generated implementation that sets the corresponding property. ```java // Both classes HumanDto and Human have property with name "fullName" // properties with the same name will be mapped implicitly @Mapper public interface HumanMapper { HumanDto toHumanDto(Human human) } ``` ```java // generates: @Override public HumanDto toHumanDto(Human human) { humanDto.setFullName( human.getFullName() ); // ... } ``` -------------------------------- ### Generated implementation for @MapMapping example Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/MapMapping.html Shows the generated implementation of the mapper method, including formatting of keys and values. ```java // generates public class SimpleMapperImpl implements SimpleMapper { @Override public Map longDateMapToStringStringMap(Map source) } { Map map = new HashMap(); } for ( java.util.Map.Entry entry : source.entrySet() ) } { String key = new DecimalFormat( "" ).format( entry.getKey() ); String value = new SimpleDateFormat( "dd.MM.yyyy" ).format( entry.getValue() ); map.put( key, value ); } // ... } } ``` -------------------------------- ### Create config with @MapperConfig Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/MapperConfig.html Example of creating a central configuration class using @MapperConfig with uses and unmappedTargetPolicy. ```java // create config @MapperConfig( uses = CustomMapperViaMapperConfig.class, unmappedTargetPolicy = ReportingPolicy.ERROR ) public interface CentralConfig { } ``` -------------------------------- ### Example 3: Mapping with expression Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/Mapping.html Shows using expression() to map Human.name to HumanDto.countNameSymbols. Note: currently works only for Java. ```java // We need map Human.name to HumanDto.countNameSymbols. // we can use expression() for it @Mapper public interface HumanMapper { @Mapping(target="countNameSymbols", expression="java(human.getName().length())") HumanDto toHumanDto(Human human) } ``` ```java // generates: @Override public HumanDto toHumanDto(Human human) { humanDto.setCountNameSymbols( human.getName().length() ); //... } ``` -------------------------------- ### Before Java 8: Using @SubclassMappings wrapper Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/SubclassMappings.html Example of using @SubclassMappings before Java 8 to wrap multiple @SubclassMapping annotations. ```java // before java 8 @Mapper public interface MyMapper { @SubclassMappings({ @SubclassMapping(source = FirstSub.class, target = FirstTargetSub.class), @SubclassMapping(source = SecondSub.class, target = SecondTargetSub.class) }) ParentTarget toParentTarget(Parent parent); } ``` -------------------------------- ### Spring component model example Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/MappingConstants.ComponentModel.html Shows how to use the SPRING constant to make the generated mapper a Spring bean retrievable via @Autowired. ```java // Spring component model @Mapper(componentModel = MappingConstants.ComponentModel.SPRING) ``` -------------------------------- ### FromToMapping Source: https://mapstruct.org/documentation/spring-extensions/api/extensions/index-all.html Represents a from-to mapping between source and target types. Provides methods to get the source, target, adapter method name, and equality check. ```APIDOC ## FromToMapping ### Description Represents a from-to mapping between source and target types. ### Constructors - `FromToMapping()` - Constructs a new empty mapping. ### Methods #### equals(Object) - **Parameters**: `obj` (Object) - Required - The object to compare. - **Returns**: boolean - True if equal, false otherwise. #### getAdapterMethodName() - **Returns**: String - The adapter method name. #### getSource() - **Returns**: String - The source type. #### getTarget() - **Returns**: String - The target type. ``` -------------------------------- ### Java 8 and later: direct @ValueMapping annotations Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ValueMappings.html Shows the Java 8+ syntax where the @ValueMappings wrapper can be omitted and multiple @ValueMapping annotations are placed directly on the method. This is equivalent to the before-Java-8 example. ```java //Java 8 and later @Mapper public interface GenderMapper { @ValueMapping(target = "M", source = "MALE"), @ValueMapping(target = "F", source = "FEMALE") GenderDto mapToDto(Gender gender); } ``` -------------------------------- ### @ConverterScan integration test setup Source: https://mapstruct.org/documentation/spring-extensions/reference/html Use @ConverterScan on a @Configuration class in a Spring integration test to automatically scan for mappers and register them in a provided ConversionService. The example shows a test class using @ExtendWith(SpringExtension.class) and autowiring the ConversionService. ```java @ExtendWith(SpringExtension.class) class ConversionServiceAdapterIntegrationTest { @Configuration @ConverterScan(basePackageClasses = MapperSpringConfig.class) static class ScanConfiguration {} @Autowired private ConversionService conversionService; [...] } ``` -------------------------------- ### Constructor with parameter, property entries, and path properties Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/internal/model/beanmapping/TargetReference.html Constructor that takes a Parameter, a list of property entries, and a list of path properties. ```java public TargetReference​(Parameter parameter, List propertyEntries, List pathProperties) ``` -------------------------------- ### init(ProcessingEnvironment processingEnv) Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/MappingProcessor.html Initializes the processor with the processing environment. ```APIDOC ## init(ProcessingEnvironment processingEnv) ### Description Initializes the processor with the processing environment. ### Method POST ### Endpoint MappingProcessor.init(ProcessingEnvironment) ### Parameters #### Request Body - **processingEnv** (ProcessingEnvironment) - Required - The processing environment provided by the annotation processing tool. ### Response #### Success Response (200) No return value. #### Response Example ``` void ``` ``` -------------------------------- ### BuilderInfo.Builder.build() Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/spi/BuilderInfo.Builder.html Creates the BuilderInfo instance. ```APIDOC ## Method: build() ### Description Creates the `BuilderInfo` using the previously set builder creation and build methods. ### Method Instance method ### Signature `public BuilderInfo build()` ### Parameters None ### Returns The created `BuilderInfo`. ### Throws - **IllegalArgumentException** - if the builder creation or build methods are `null`. ### Example ```java BuilderInfo.Builder builder = new BuilderInfo.Builder(); // set builder creation and build methods BuilderInfo info = builder.build(); ``` ``` -------------------------------- ### getParameter Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/internal/model/HelperMethod.html Abstract method to get a parameter. ```APIDOC ## getParameter ### Description Abstract method to get a parameter. ### Returns - (Parameter) - the parameter ``` -------------------------------- ### Example 1: Using @Context parameters for passing data to hand-written property mapping methods and @BeforeMapping methods Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/Context.html Shows how to use multiple @Context parameters in a mapping method and how they are passed to hand-written property mapping methods and @BeforeMapping methods. The generated code demonstrates that @Context parameters are passed to before-mapping methods and used in the generated mapping method. ```java // multiple @Context parameters can be added public abstract CarDto toCar(Car car, @Context VehicleRegistration context, @Context Locale localeToUse); protected OwnerManualDto translateOwnerManual(OwnerManual ownerManual, @Context Locale locale) { // manually implemented logic to translate the OwnerManual with the given Locale } @BeforeMapping protected void registerVehicle(Vehicle mappedVehicle, @Context VehicleRegistration context) { context.register( mappedVehicle ); } @BeforeMapping protected void notCalled(Vehicle mappedVehicle, @Context DifferentMappingContextType context) { // not called, because no context parameter of type DifferentMappingContextType is available // within toCar(Car, VehicleRegistration, Locale) } // generates: public CarDto toCar(Car car, VehicleRegistration context, Locale localeToUse) { registerVehicle( car, context ); if ( car == null ) { return null; } CarDto carDto = new CarDto(); carDto.setOwnerManual( translateOwnerManual( car.getOwnerManual(), localeToUse ) ); // more generated mapping code return carDto; } ``` -------------------------------- ### getBoxedEquivalent() Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/internal/model/common/Type.html Gets the boxed equivalent type if the type is primitive. ```APIDOC ## getBoxedEquivalent() ### Description Gets the boxed equivalent type if the type is primitive, e.g., int will return Integer. ### Method getBoxedEquivalent ### Signature `public Type getBoxedEquivalent()` ### Returns - **Type** - The boxed equivalent type. ``` -------------------------------- ### build() Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/internal/model/Javadoc.Builder.html Builds and returns the Javadoc instance with the configured values. ```APIDOC ## Method: build() ### Description Builds and returns the Javadoc instance with the configured values. ### Signature `public Javadoc build()` ### Parameters None. ### Returns A Javadoc object constructed with the previously set values. ``` -------------------------------- ### getThrownTypes(Accessor) Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/internal/model/common/TypeFactory.html Gets the thrown types for the given accessor method. ```APIDOC ## getThrownTypes(Accessor) ### Description Gets the thrown types for the given accessor method. ### Parameters - **accessor** (Accessor) - The accessor method. ### Returns - **List** - The thrown types of the accessor method. ``` -------------------------------- ### build() Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/internal/model/beanmapping/SourceReference.BuilderFromProperty.html Builds and returns the SourceReference instance. ```APIDOC ## build() ### Description Builds and returns the SourceReference instance. ### Method Instance Method ### Signature `public SourceReference build()` ### Returns - `SourceReference` - The built SourceReference. ``` -------------------------------- ### getThrownTypes(ExecutableType) Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/internal/model/common/TypeFactory.html Gets the thrown types for the given executable method. ```APIDOC ## getThrownTypes(ExecutableType) ### Description Gets the thrown types for the given executable method. ### Parameters - **method** (ExecutableType) - The executable method. ### Returns - **List** - The thrown types of the executable method. ``` -------------------------------- ### Constructor with parameter and property entries Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/internal/model/beanmapping/TargetReference.html Constructor that takes a Parameter and a list of property entries. ```java public TargetReference​(Parameter parameter, List propertyEntries) ``` -------------------------------- ### getReturnType(ExecutableType) Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/internal/model/common/TypeFactory.html Gets the return type for the given executable method. ```APIDOC ## getReturnType(ExecutableType) ### Description Gets the return type for the given executable method. ### Parameters - **method** (ExecutableType) - The executable method. ### Returns - **Type** - The return type of the executable method. ``` -------------------------------- ### ShelveDTO class Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/control/MappingControl.html Example DTO class representing a shelve with a coolBeer property. ```java public class ShelveDTO { private CoolBeerDTO coolBeer; public CoolBeerDTO getCoolBeer() { return coolBeer; } public void setCoolBeer(CoolBeerDTO coolBeer) { this.coolBeer = coolBeer; } } ``` -------------------------------- ### FromToMapping() Source: https://mapstruct.org/documentation/spring-extensions/api/extensions/org/mapstruct/extensions/spring/converter/FromToMapping.html Constructs a new FromToMapping instance. ```APIDOC ## Constructor: FromToMapping() ### Description Creates a new instance of the FromToMapping class. ### Method Constructor ### Signature `public FromToMapping()` ### Parameters None ### Returns A new FromToMapping object. ### Example ```java FromToMapping mapping = new FromToMapping(); ``` ``` -------------------------------- ### FridgeDTO class Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/control/MappingControl.html Example DTO class representing a fridge with a shelve property. ```java public class FridgeDTO { private ShelveDTO shelve; public ShelveDTO getShelve() { return shelve; } public void setShelve(ShelveDTO shelve) { this.shelve = shelve; } } ``` -------------------------------- ### init(ProcessingEnvironment) Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/MappingProcessor.html Initializes the processor with the processing environment. This method is specified by the Processor interface and overrides AbstractProcessor.init(). ```APIDOC ## init(ProcessingEnvironment) ### Description Initializes the processor with the processing environment. This method is specified by the Processor interface and overrides AbstractProcessor.init(). ### Method init ### Signature ```java public void init(ProcessingEnvironment processingEnv) ``` ### Parameters - **processingEnv** (ProcessingEnvironment) - Required - The processing environment provided by the annotation processing tool. ``` -------------------------------- ### Iterating over enum constants Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/internal/model/common/Assignment.AssignmentType.html Example loop that iterates over the enum constants and prints them. ```java for (Assignment.AssignmentType c : Assignment.AssignmentType.values()) System.out.println(c); ``` -------------------------------- ### BuilderInfo.Builder() Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/spi/BuilderInfo.Builder.html Constructs a new BuilderInfo.Builder instance. ```APIDOC ## Constructor: BuilderInfo.Builder() ### Description Creates a new builder instance for constructing `BuilderInfo` objects. ### Method Constructor ### Signature `public Builder()` ### Parameters None ### Returns A new `BuilderInfo.Builder` instance. ### Example ```java BuilderInfo.Builder builder = new BuilderInfo.Builder(); ``` ``` -------------------------------- ### @BeanMapping Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/BeanMapping.html Documentation for the @BeanMapping annotation, including its optional elements and an example of usage. ```APIDOC ## @BeanMapping ### Description Configures the mapping between two bean types. Unless otherwise specified these properties are inherited to the generated bean mapping methods. Either `resultType()`, `qualifiedBy()` or `nullValueMappingStrategy()` must be specified. ### Annotation `@Target(METHOD)` `@Retention(CLASS)` ### Optional Elements #### resultType - **Type**: `Class` - **Default**: `void.class` - **Description**: Specifies the result type of the factory method to be used in case several factory methods qualify. This property is not inherited to generated mapping methods. #### qualifiedBy - **Type**: `Class[]` - **Default**: `{}` - **Description**: A qualifier can be specified to aid the selection process of a suitable factory method or filtering applicable `@BeforeMapping` / `@AfterMapping` methods. This is useful in case multiple factory methods qualify and result in an 'Ambiguous factory methods' error. #### qualifiedByName - **Type**: `String[]` - **Default**: `{}` - **Description**: Similar to `qualifiedBy()`, but used in combination with `@Named` in case no custom qualifier annotation is defined. #### nullValueMappingStrategy - **Type**: `NullValueMappingStrategy` - **Default**: `org.mapstruct.NullValueMappingStrategy.RETURN_NULL` - **Description**: The strategy to be applied when `null` is passed as source bean argument value to this bean mapping. If no strategy is configured, the strategy given via `MapperConfig.nullValueMappingStrategy()` or `Mapper.nullValueMappingStrategy()` will be applied. #### nullValuePropertyMappingStrategy - **Type**: `NullValuePropertyMappingStrategy` - **Default**: (not specified) - **Description**: The strategy to be applied when a source bean property is `null` or not present. #### ignoreByDefault - **Type**: `boolean` - **Default**: (not specified) - **Description**: Default ignore all mappings. #### ignoreUnmappedSourceProperties - **Type**: `String[]` - **Default**: (not specified) - **Description**: Unmapped source properties to be ignored. #### mappingControl - **Type**: `Class` - **Default**: (not specified) - **Description**: Allows detailed control over the mapping process. #### nullValueCheckStrategy - **Type**: `NullValueCheckStrategy` - **Default**: (not specified) - **Description**: Determines when to include a null check on the source property value of a bean mapping. #### subclassExhaustiveStrategy - **Type**: `SubclassExhaustiveStrategy` - **Default**: (not specified) - **Description**: Determines how to handle missing implementation for super classes when using the `SubclassMapping`. #### unmappedSourcePolicy - **Type**: `ReportingPolicy` - **Default**: (not specified) - **Description**: How unmapped properties of the source type of a mapping should be reported. #### unmappedTargetPolicy - **Type**: `ReportingPolicy` - **Default**: (not specified) - **Description**: How unmapped properties of the target type of a mapping should be reported. #### builder - **Type**: `Builder` - **Default**: (not specified) - **Description**: The information that should be used for the builder mappings. ### Example: Determining the result type ```java // When result types have an inheritance relation, selecting either mapping method Mapping or factory method // BeanMapping can be become ambiguous. Parameter resultType() can be used. public class FruitFactory { public Apple createApple() { return new Apple(); } public Orange createOrange() { return new Orange(); } } @Mapper(uses = FruitFactory.class) public interface FruitMapper { @BeanMapping(resultType = Apple.class) Fruit toFruit(FruitDto fruitDto); } ``` ```java // generates public class FruitMapperImpl implements FruitMapper { @Override public Fruit toFruit(FruitDto fruitDto) { Apple fruit = fruitFactory.createApple(); // ... } } ``` ``` -------------------------------- ### Generated Javadoc from attributes Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/Javadoc.html Output Javadoc generated from the @Javadoc attribute example above. ```java /** * This is the description * * @author author1 * @author author2 * * @deprecated Use {@link OtherMapper} instead * @since 0.1 */ ``` -------------------------------- ### getOptions Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/internal/model/MappingBuilderContext.html Returns the Options instance containing processor options. ```APIDOC ## getOptions ### Description Returns the Options instance containing processor options. ### Method GET ### Endpoint /getOptions ### Parameters None ### Response #### Success Response (200) - **Options** - The options instance. #### Response Example ```json { "options": "Options" } ``` ``` -------------------------------- ### getTypeElement(TypeMirror) Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/spi/DefaultBuilderProvider.html Protected helper method to get the TypeElement for a given TypeMirror. ```APIDOC ### Method #### getTypeElement(TypeMirror) Finds the `TypeElement` for the given `TypeMirror`. **Signature:** ```java protected TypeElement getTypeElement(TypeMirror type) ``` **Parameters:** - `type` (TypeMirror) - the type mirror **Returns:** - `TypeElement` - the corresponding type element ``` -------------------------------- ### getPermittedSubclasses() Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/internal/model/common/Type.html Gets the list of permitted subclasses for a Java 17+ sealed class. ```APIDOC ## getPermittedSubclasses() ### Description Returns the list of permitted TypeMirrors for the Java 17+ sealed class. ### Method getPermittedSubclasses ### Signature `public List getPermittedSubclasses()` ### Returns - **List** - The list of permitted subclasses. ``` -------------------------------- ### markAsFullyInitialized Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/internal/model/source/MappingMethodOptions.html Marks the options as fully initialized. ```APIDOC ## markAsFullyInitialized ### Description Marks the options as fully initialized. ### Method markAsFullyInitialized ### Signature `public void markAsFullyInitialized()` ``` -------------------------------- ### Mapper build() Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/internal/model/Mapper.Builder.html Builds and returns a Mapper instance. ```APIDOC ## Mapper build() ### Description Builds the Mapper instance using the configured builder properties. ### Method Build method ### Signature `public Mapper build()` ### Parameters None ### Returns A Mapper instance. ### Example ```java Mapper mapper = new Mapper.Builder() .element(typeElement) .build(); ``` ``` -------------------------------- ### CoolBeerDTO class Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/control/MappingControl.html Example DTO class representing a cool beer with a beerCount property. ```java public class CoolBeerDTO { private String beerCount; public String getBeerCount() { return beerCount; } public void setBeerCount(String beerCount) { this.beerCount = beerCount; } } ``` -------------------------------- ### @MapperConfig Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/MapperConfig.html Documentation for the @MapperConfig annotation, including its declaration, optional elements, and usage examples. ```APIDOC ## @MapperConfig ### Description Marks a class or interface as configuration source for generated mappers. This allows to share common configurations between several mapper classes. Generally, any settings given via `Mapper` take precedence over the settings given via the referenced `MapperConfig`. The lists of referenced mappers given via `Mapper.uses()` and `uses()` will be merged. ### Annotation Declaration ```java @Target(TYPE) @Retention(CLASS) public @interface MapperConfig ``` ### Optional Elements #### uses - **Type**: `Class[]` - **Default**: (not specified) - **Description**: The mapper types used by this mapper. #### builder - **Type**: `Builder` - **Default**: (not specified) - **Description**: The information that should be used for the builder mappings. #### collectionMappingStrategy - **Type**: `CollectionMappingStrategy` - **Default**: (not specified) - **Description**: The strategy to be applied when propagating the value of collection-typed properties. #### componentModel - **Type**: `String` - **Default**: (not specified) - **Description**: Specifies the component model to which the generated mapper should adhere. #### disableSubMappingMethodsGeneration - **Type**: `boolean` - **Default**: (not specified) - **Description**: If MapStruct could not find another mapping method or apply an automatic conversion it will try to generate a sub-mapping method between the two beans. #### implementationName - **Type**: `String` - **Default**: (not specified) - **Description**: Specifies the name of the implementation class. #### implementationPackage - **Type**: `String` - **Default**: (not specified) - **Description**: Specifies the target package for the generated implementation. #### imports - **Type**: `Class[]` - **Default**: (not specified) - **Description**: Additional types for which an import statement is to be added to the generated mapper implementation class. #### injectionStrategy - **Type**: `InjectionStrategy` - **Default**: (not specified) - **Description**: Determines whether to use field or constructor injection. #### mappingControl - **Type**: `Class` - **Default**: (not specified) - **Description**: Allows detailed control over the mapping process. #### mappingInheritanceStrategy - **Type**: `MappingInheritanceStrategy` - **Default**: (not specified) - **Description**: The strategy to use for applying method-level configuration annotations of prototype methods in the interface annotated with this annotation. #### nullValueCheckStrategy - **Type**: `NullValueCheckStrategy` - **Default**: (not specified) - **Description**: Determines when to include a null check on the source property value of a bean mapping. #### nullValueIterableMappingStrategy - **Type**: `NullValueMappingStrategy` - **Default**: (not specified) - **Description**: The strategy to be applied when `null` is passed as source argument value to an `IterableMapping`. #### nullValueMapMappingStrategy - **Type**: `NullValueMappingStrategy` - **Default**: (not specified) - **Description**: The strategy to be applied when `null` is passed as source argument value to a `MapMapping`. #### nullValueMappingStrategy - **Type**: `NullValueMappingStrategy` - **Default**: (not specified) - **Description**: The strategy to be applied when `null` is passed as source argument value to mapping methods. #### nullValuePropertyMappingStrategy - **Type**: `NullValuePropertyMappingStrategy` - **Default**: (not specified) - **Description**: The strategy to be applied when a source bean property is `null` or not present. #### subclassExhaustiveStrategy - **Type**: `SubclassExhaustiveStrategy` - **Default**: (not specified) - **Description**: Determines how to handle missing implementation for super classes when using the `SubclassMapping`. #### suppressTimestampInGenerated - **Type**: `boolean` - **Default**: (not specified) - **Description**: Flag indicating whether the addition of a time stamp in the `@Generated` annotation should be suppressed. #### typeConversionPolicy - **Type**: `ReportingPolicy` - **Default**: (not specified) - **Description**: How lossy (narrowing) conversion, for instance: long to integer should be reported. #### unexpectedValueMappingException - **Type**: `Class` - **Default**: (not specified) - **Description**: Exception that should be thrown by the generated code if no mapping matches for enums. #### unmappedSourcePolicy - **Type**: `ReportingPolicy` - **Default**: (not specified) - **Description**: How unmapped properties of the source type of a mapping should be reported. #### unmappedTargetPolicy - **Type**: `ReportingPolicy` - **Default**: (not specified) - **Description**: How unmapped properties of the target type of a mapping should be reported. ### Example ```java // create config @MapperConfig( uses = CustomMapperViaMapperConfig.class, unmappedTargetPolicy = ReportingPolicy.ERROR ) public interface CentralConfig { } ``` ```java // use config @Mapper(config = CentralConfig.class, uses = { CustomMapperViaMapper.class } ) public interface SourceTargetMapper { // ... } ``` ```java // result after applying CentralConfig @Mapper( uses = { CustomMapperViaMapper.class, CustomMapperViaMapperConfig.class }, unmappedTargetPolicy = ReportingPolicy.ERROR ) public interface SourceTargetMapper { // ... } ``` ### See Also - `Mapper.config()` ``` -------------------------------- ### init(ProcessingEnvironment) Source: https://mapstruct.org/documentation/spring-extensions/api/extensions/org/mapstruct/extensions/spring/converter/Generator.html Initializes the generator with the annotation processing environment, storing it for later use. ```APIDOC ## init(ProcessingEnvironment) ### Description Initializes the generator with the annotation processing environment, storing it for later use. ### Method init ### Signature public final void init(ProcessingEnvironment processingEnv) ### Parameters - **processingEnv** (ProcessingEnvironment) - Required - The annotation processing environment. ### Returns void ``` -------------------------------- ### CharWrapperToStringConversion() Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/internal/conversion/CharWrapperToStringConversion.html Constructor for creating a new CharWrapperToStringConversion instance. ```APIDOC ## Constructor: CharWrapperToStringConversion() ### Description Creates a new instance of the CharWrapperToStringConversion class. ### Method Constructor ### Signature ```java public CharWrapperToStringConversion() ``` ### Parameters None ### Returns A new CharWrapperToStringConversion instance. ``` -------------------------------- ### Iterating over MethodType constants Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/spi/MethodType.html Example loop that prints each enum constant using the values() method. ```java for (MethodType c : MethodType.values()) System.out.println(c); ``` -------------------------------- ### Use config with @Mapper Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/MapperConfig.html Example of using the central configuration in a mapper with @Mapper(config = CentralConfig.class). ```java // use config @Mapper(config = CentralConfig.class, uses = { CustomMapperViaMapper.class } ) public interface SourceTargetMapper { // ... } ``` -------------------------------- ### create(BuilderInfo, Type, TypeFactory, TypeUtils) Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/internal/model/common/BuilderType.html Static factory method to create a BuilderType instance. ```APIDOC ## create(BuilderInfo, Type, TypeFactory, TypeUtils) ### Description Static factory method to create a BuilderType instance. ### Method `public static BuilderType create(BuilderInfo builderInfo, Type typeToBuild, TypeFactory typeFactory, TypeUtils typeUtils)` ### Parameters - **builderInfo** (BuilderInfo) - The builder information. - **typeToBuild** (Type) - The type to build. - **typeFactory** (TypeFactory) - The type factory. - **typeUtils** (TypeUtils) - The type utilities. ### Returns - **BuilderType** - the created BuilderType instance ``` -------------------------------- ### getSupportedOptions() Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/MappingProcessor.html Returns the supported options for the processor. This method is specified by the Processor interface and overrides AbstractProcessor.getSupportedOptions(). ```APIDOC ## getSupportedOptions() ### Description Returns the supported options for the processor. This method is specified by the Processor interface and overrides AbstractProcessor.getSupportedOptions(). ### Method getSupportedOptions ### Signature ```java public Set getSupportedOptions() ``` ### Returns - **Set** - The set of supported options. ``` -------------------------------- ### @Qualifier Annotation Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/Qualifier.html Documentation for the @Qualifier annotation, including its declaration, usage locations, examples, and notes. ```APIDOC ## @Qualifier ### Description Declares an annotation type to be a qualifier. Qualifier annotations allow unambiguously identify a suitable mapping method in case several methods qualify to map a bean property, iterable element etc. ### Usage Can be used in: - `Mapping.qualifiedBy()` - `BeanMapping.qualifiedBy()` - `IterableMapping.qualifiedBy()` - `MapMapping.keyQualifiedBy()` - `MapMapping.valueQualifiedBy()` - `SubclassMapping.qualifiedBy()` ### Example ```java // create qualifiers @Qualifier @Target(ElementType.TYPE) @Retention(RetentionPolicy.CLASS) public @interface TitleTranslator {} @Qualifier @Target(ElementType.METHOD) @Retention(RetentionPolicy.CLASS) public @interface EnglishToGerman {} @Qualifier @Target(ElementType.METHOD) @Retention(RetentionPolicy.CLASS) public @interface GermanToEnglish {} ``` ```java // we can create class with map methods @TitleTranslator public class Titles { @EnglishToGerman public String translateTitleEnglishToGerman(String title) { // some mapping logic } @GermanToEnglish public String translateTitleGermanToEnglish(String title) { // some mapping logic } } ``` ```java // usage @Mapper( uses = Titles.class ) public interface MovieMapper { @Mapping( target = "title", qualifiedBy = { TitleTranslator.class, EnglishToGerman.class } ) GermanRelease toGerman( OriginalRelease movies ); } ``` ```java // generates public class MovieMapperImpl implements MovieMapper { private final Titles titles = new Titles(); @Override public GermanRelease toGerman(OriginalRelease movies) { if ( movies == null ) { return null; } GermanRelease germanRelease = new GermanRelease(); germanRelease.setTitle( titles.translateTitleEnglishToGerman( movies.getTitle() ) ); return germanRelease; } } ``` ### Note Qualifiers should have `RetentionPolicy.CLASS`. ### See Also - `Named` ``` -------------------------------- ### create(ProcessingEnvironment, VersionInformation, TypeElement) Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/internal/util/ElementUtils.html Static factory method to create an ElementUtils instance. ```APIDOC ## create(ProcessingEnvironment, VersionInformation, TypeElement) ### Description Creates a new ElementUtils instance. ### Method static ElementUtils create(ProcessingEnvironment processingEnvironment, VersionInformation info, TypeElement mapperElement) ### Parameters - **processingEnvironment** (ProcessingEnvironment) - Required - The processing environment. - **info** (VersionInformation) - Required - Version information. - **mapperElement** (TypeElement) - Required - The mapper type element. ### Returns - **ElementUtils** - A new ElementUtils instance. ``` -------------------------------- ### getParameters(DeclaredType, ExecutableElement) Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/internal/model/common/TypeFactory.html Gets the parameters for the given executable method within the including type. ```APIDOC ## getParameters(DeclaredType, ExecutableElement) ### Description Gets the parameters for the given executable method within the including type. ### Parameters - **includingType** (DeclaredType) - The type on which's scope the method type shall be evaluated. - **method** (ExecutableElement) - The executable method. ### Returns - **List** - The parameters of the executable method. ``` -------------------------------- ### getParameters(DeclaredType, Accessor) Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/internal/model/common/TypeFactory.html Gets the parameters for the given accessor method within the including type. ```APIDOC ## getParameters(DeclaredType, Accessor) ### Description Gets the parameters for the given accessor method within the including type. ### Parameters - **includingType** (DeclaredType) - The type on which's scope the method type shall be evaluated. - **accessor** (Accessor) - The accessor method. ### Returns - **List** - The parameters of the accessor method. ``` -------------------------------- ### BuilderInfo.Builder.builderCreationMethod(ExecutableElement) Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/spi/BuilderInfo.Builder.html Sets the creation method for the builder. ```APIDOC ## Method: builderCreationMethod(ExecutableElement) ### Description Sets the creation method for the builder. This method is used to specify how the builder is created. ### Method Instance method ### Signature `public BuilderInfo.Builder builderCreationMethod(ExecutableElement method)` ### Parameters - **method** (ExecutableElement) - Required - The creation method for the builder. ### Returns This builder instance for chaining. ### See Also - `BuilderInfo.getBuilderCreationMethod()` ### Example ```java BuilderInfo.Builder builder = new BuilderInfo.Builder(); builder.builderCreationMethod(creationMethod); ``` ``` -------------------------------- ### BigDecimalToBigIntegerConversion() Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/internal/conversion/BigDecimalToBigIntegerConversion.html Constructor for creating a new BigDecimalToBigIntegerConversion instance. ```APIDOC ## Constructor ### Signature ```java public BigDecimalToBigIntegerConversion() ``` ### Description Creates a new instance of the conversion provider for converting between BigDecimal and BigInteger. ``` -------------------------------- ### getFromToMappings() Source: https://mapstruct.org/documentation/spring-extensions/api/extensions/org/mapstruct/extensions/spring/converter/ConversionServiceAdapterDescriptor.html Returns the list of from-to mappings. ```APIDOC ## getFromToMappings() ### Description Returns the list of FromToMapping objects. ### Method Getter ### Returns - **List** - The list of mappings. ``` -------------------------------- ### Iterate over SubclassExhaustiveStrategy constants Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/SubclassExhaustiveStrategy.html Example iteration over the enum constants using the values() method, printing each constant. ```java for (SubclassExhaustiveStrategy c : SubclassExhaustiveStrategy.values()) System.out.println(c); ``` -------------------------------- ### @TargetType Annotation Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/TargetType.html Documentation for the @TargetType annotation in MapStruct, including its declaration, usage, and generated code example. ```APIDOC ## @TargetType ### Description Declares a parameter of a custom mapping method to be populated with the target type of the mapping. Not more than one parameter can be declared as `@TargetType` and that parameter needs to be of type `Class` (may be parameterized), or a super-type of it. ### Annotation Declaration ```java @Target(PARAMETER) @Retention(CLASS) public @interface TargetType ``` ### Usage Example ```java public class EntityFactory { public T createEntity(@TargetType Class entityClass) { return // ... custom factory logic } } @Mapper(uses = EntityFactory.class) public interface CarMapper { CarEntity carDtoToCar(CarDto dto); } ``` ### Generated Code Example ```java public class CarMapperImpl implements CarMapper { private final EntityFactory entityFactory = new EntityFactory(); @Override public CarEntity carDtoToCar(CarDto dto) { if ( dto == null ) { return null; } CarEntity carEntity = entityFactory.createEntity( CarEntity.class ); return carEntity; } } ``` ### Author Andreas Gudian ``` -------------------------------- ### @SourceParameterCondition Annotation Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/SourceParameterCondition.html Documentation for the @SourceParameterCondition annotation, including its declaration, usage, parameters, return value, and examples. ```APIDOC ## @SourceParameterCondition ### Description Marks a method as a check method to determine if a source parameter needs to be mapped. By default, source parameters are checked against null unless they are primitives. Check methods must return boolean and can accept the mapping source parameter and @Context parameters. ### Annotation Declaration ```java @Target(METHOD) @Retention(CLASS) public @interface SourceParameterCondition ``` ### Usage - **Target**: METHOD - **Retention**: CLASS - **Since**: 1.6 - **Author**: Filip Hrisafov - **See Also**: @Condition ### Parameters - **Mapping source parameter** (type: any) - Required - The source parameter to check. - **@Context parameter** (type: any) - Optional - Additional context parameters. ### Return Value - **boolean** - Indicates whether the source parameter needs to be mapped. ### Example ```java public class PresenceCheckUtils { @SourceParameterCondition public static boolean isDefined(Car car) { return car != null && car.getId() != null; } } @Mapper(uses = PresenceCheckUtils.class) public interface CarMapper { CarDto map(Car car); } ``` ### Generated Implementation Example ```java public class CarMapperImpl implements CarMapper { @Override public CarDto map(Car car) { if ( !PresenceCheckUtils.isDefined( car ) ) { return null; } CarDto carDto = new CarDto(); carDto.setId( car.getId() ); // ... return carDto; } } ``` ``` -------------------------------- ### Constructor: AccessorNamingUtils(AccessorNamingStrategy) Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/ap/internal/util/AccessorNamingUtils.html Creates an AccessorNamingUtils instance with the given AccessorNamingStrategy. This constructor is used to initialize the utility for working with accessor naming conventions. ```APIDOC ## Constructor: AccessorNamingUtils(AccessorNamingStrategy) ### Description Creates an AccessorNamingUtils instance with the given AccessorNamingStrategy. This constructor is used to initialize the utility for working with accessor naming conventions. ### Signature `public AccessorNamingUtils(AccessorNamingStrategy accessorNamingStrategy)` ### Parameters - `accessorNamingStrategy` (AccessorNamingStrategy) - Required - The strategy to use for naming accessor methods. ``` -------------------------------- ### Example 3: Using @Context parameters for creating an entity object by calling an @ObjectFactory method Source: https://mapstruct.org/documentation/stable/api/org/mapstruct/Context.html Shows how to use an @Context parameter with an object factory to create entity objects. The generated code calls the factory method with the context parameter to obtain the entity instance. ```java // type of the context parameter public class ContextObjectFactory { @PersistenceContext(unitName = "my-unit") private EntityManager em; @ObjectFactory public Valve create( String id ) { Query query = em.createNamedQuery("Valve.findById"); query.setParameter("id", id); Valve result = query.getSingleResult(); if ( result != null ) { result = new Valve( id ); } return result; } } @Mapper public interface ContextWithObjectFactoryMapper { Valve map(ValveDto dto, @Context ContextObjectFactory factory, String id); } // generates: public class ContextWithObjectFactoryMapperImpl implements ContextWithObjectFactoryMapper { @Override public Valve map(ValveDto dto, ContextObjectFactory factory, String id) { if ( dto == null ) { return null; } Valve valve = factory.create( id ); valve.setOneWay( dto.isOneWay() ); return valve; } } ```