Package org.mapstruct

Annotation Type Mapping


Configures the mapping of one bean attribute.

The name of the mapped attribute or constant is to be specified via target(). For mapped bean attributes it is assumed by default that the attribute has the same name in the source bean. Alternatively, one of source(), expression() or constant() can be specified to define the property source.

In addition, the attributes dateFormat() and qualifiedBy() may be used to further define the mapping.

Example 1: Implicitly mapping fields with the same name:


 // 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)
 }
 

 // generates:
 @Override
 public HumanDto toHumanDto(Human human) {
    humanDto.setFullName( human.getFullName() );
    // ...
 }
 

Example 2: Mapping properties with different names


 // 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)
 }
 

 // generates:
 @Override
 public HumanDto toHumanDto(Human human) {
     humanDto.setCompany( human.getCompanyName() );
      // ...
 }
 

Example 3: Mapping with expression IMPORTANT NOTE: Now it works only for 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)
 }
 

 // generates:
@Override
 public HumanDto toHumanDto(Human human) {
    humanDto.setCountNameSymbols( human.getName().length() );
    //...
 }
 

Example 4: Mapping to constant


 // We need map HumanDto.name to string constant "Unknown"
 // we can use constant() for it
 @Mapper
 public interface HumanMapper {
    @Mapping(target="name", constant="Unknown")
    HumanDto toHumanDto(Human human)
 }
 

 // generates
 @Override
 public HumanDto toHumanDto(Human human) {
   humanDto.setName( "Unknown" );
   // ...
 }
 

Example 5: Mapping with default value


 // We need map Human.name to HumanDto.fullName, but if Human.name == null, then set value "Somebody"
 // we can use defaultValue() or defaultExpression() for it
 @Mapper
 public interface HumanMapper {
    @Mapping(source="name", target="fullName", defaultValue="Somebody")
    HumanDto toHumanDto(Human human)
 }
 

 // generates
 @Override
 public HumanDto toHumanDto(Human human) {
    if ( human.getName() != null ) {
       humanDto.setFullName( human.getName() );
    }
    else {
       humanDto.setFullName( "Somebody" );
    }
   // ...
 }
 
Author:
Gunnar Morling
  • Required Element Summary

    Required Elements
    Modifier and Type
    Required Element
    Description
    The target name of the configured property as defined by the JavaBeans specification.
  • Optional Element Summary

    Optional Elements
    Modifier and Type
    Optional Element
    Description
    A conditionExpression String based on which the specified property is to be checked whether it is present or not.
    Class<? extends Annotation>[]
    A qualifier can be specified to aid the selection process of a suitable presence check method.
    String-based form of qualifiers for condition / presence check methods; When looking for a suitable presence check method for a given property, MapStruct will only consider those methods carrying directly or indirectly (i.e. on the class-level) a Named annotation for each of the specified qualifier names.
    A constant String based on which the specified target property is to be set.
    A format string as processable by SimpleDateFormat if the attribute is mapped from String to Date or vice-versa.
    A defaultExpression String based on which the specified target property is to be set if and only if the specified source property is null.
    In case the source property is null, the provided default String value is set.
    One or more properties of the result type on which the mapped property depends.
    An expression String based on which the specified target property is to be set.
    boolean
    Whether the property specified via target() should be ignored by the generated mapping method or not.
    Specifies the locale to be used when processing dateFormat() or numberFormat().
    Class<? extends Annotation>
    Allows detailed control over the mapping process.
    Determines when to include a null check on the source property value of a bean mapping.
    The strategy to be applied when the source property is null or not present.
    A format string as processable by DecimalFormat if the annotated method maps from a Number to a String or vice-versa.
    Class<? extends Annotation>[]
    A qualifier can be specified to aid the selection process of a suitable mapper.
    String-based form of qualifiers; When looking for a suitable mapping method for a given property, MapStruct will only consider those methods carrying directly or indirectly (i.e. on the class-level) a Named annotation for each of the specified qualifier names.
    Specifies the result type of the mapping method to be used in case multiple mapping methods qualify.
    The source to use for this mapping.
  • Element Details

    • target

      String target
      The target name of the configured property as defined by the JavaBeans specification. The same target property must not be mapped more than once.

      If used to map an enum constant, the name of the constant member is to be given. In this case, several values from the source enum may be mapped to the same value of the target enum.

      Returns:
      The target name of the configured property or enum constant
    • source

      String source
      The source to use for this mapping. This can either be:
      1. The source name of the configured property as defined by the JavaBeans specification.

        This may either be a simple property name (e.g. "address") or a dot-separated property path (e.g. "address.city" or "address.city.name"). In case the annotated method has several source parameters, the property name must qualified with the parameter name, e.g. "addressParam.city".

      2. When no matching property is found, MapStruct looks for a matching parameter name instead.
      3. When used to map an enum constant, the name of the constant member is to be given.
      This attribute can not be used together with constant() or expression().
      Returns:
      The source name of the configured property or enum constant.
      Default:
      ""
    • dateFormat

      String dateFormat
      A format string as processable by SimpleDateFormat if the attribute is mapped from String to Date or vice-versa. Will be ignored for all other attribute types and when mapping enum constants.

      If the locale() is also specified, the format will consider the specified locale when processing the date. Otherwise, the system's default locale will be used.

      Returns:
      A date format string as processable by SimpleDateFormat.
      See Also:
      Default:
      ""
    • numberFormat

      String numberFormat
      A format string as processable by DecimalFormat if the annotated method maps from a Number to a String or vice-versa. Will be ignored for all other element types.

      If the locale() is also specified, the number format will be applied in the context of the given locale. Otherwise, the system's default locale will be used to process the number format.

      Returns:
      A decimal format string as processable by DecimalFormat.
      See Also:
      Default:
      ""
    • locale

      String locale
      Specifies the locale to be used when processing dateFormat() or numberFormat().

      The locale should be a plain tag representing the language, such as "en" for English, "de" for German, etc.

      If no locale is specified, the system's default locale will be used.

      Returns:
      A string representing the locale to be used when formatting dates or numbers.
      Default:
      ""
    • constant

      String constant
      A constant String based on which the specified target property is to be set.

      When the designated target property is of type:

      1. primitive or boxed (e.g. java.lang.Long).

        MapStruct checks whether the primitive can be assigned as valid literal to the primitive or boxed type.

        • If possible, MapStruct assigns as literal.
        • If not possible, MapStruct will try to apply a user defined mapping method.
      2. other

        MapStruct handles the constant as String. The value will be converted by applying a matching method, type conversion method or built-in conversion.

      You can use qualifiedBy() or qualifiedByName() to force the use of a conversion method even when one would not apply. (e.g. String to String)

      This attribute can not be used together with source(), defaultValue(), defaultExpression() or expression().

      Returns:
      A constant String constant specifying the value for the designated target property
      Default:
      ""
    • expression

      String expression
      An expression String based on which the specified target property is to be set.

      Currently, Java is the only supported "expression language" and expressions must be given in form of Java expressions using the following format: java(<EXPRESSION>). For instance the mapping:

      
       @Mapping(
           target = "someProp",
           expression = "java(new TimeAndFormat( s.getTime(), s.getFormat() ))"
       )
       

      will cause the following target property assignment to be generated:

      targetBean.setSomeProp( new TimeAndFormat( s.getTime(), s.getFormat() ) ).

      Any types referenced in expressions must be given via their fully-qualified name. Alternatively, types can be imported via Mapper.imports().

      This attribute can not be used together with source(), defaultValue(), defaultExpression(), qualifiedBy(), qualifiedByName() or constant().

      Returns:
      An expression specifying the value for the designated target property
      Default:
      ""
    • defaultExpression

      String defaultExpression
      A defaultExpression String based on which the specified target property is to be set if and only if the specified source property is null.

      Currently, Java is the only supported "expression language" and expressions must be given in form of Java expressions using the following format: java(<EXPRESSION>). For instance the mapping:

      
       @Mapping(
           target = "someProp",
           defaultExpression = "java(new TimeAndFormat( s.getTime(), s.getFormat() ))"
       )
       

      will cause the following target property assignment to be generated:

      targetBean.setSomeProp( new TimeAndFormat( s.getTime(), s.getFormat() ) ).

      Any types referenced in expressions must be given via their fully-qualified name. Alternatively, types can be imported via Mapper.imports().

      This attribute can not be used together with expression(), defaultValue() or constant().

      Returns:
      An expression specifying a defaultValue for the designated target property if the designated source property is null
      Since:
      1.3
      Default:
      ""
    • ignore

      boolean ignore
      Whether the property specified via target() should be ignored by the generated mapping method or not. This can be useful when certain attributes should not be propagated from source to target or when properties in the target object are populated using a decorator and thus would be reported as unmapped target property by default.

      If you have multiple properties to ignore, you can use the Ignored annotation instead and group them all at once.

      Returns:
      true if the given property should be ignored, false otherwise
      Default:
      false
    • qualifiedBy

      Class<? extends Annotation>[] qualifiedBy
      A qualifier can be specified to aid the selection process of a suitable mapper. This is useful in case multiple mapping methods (hand written or generated) qualify and thus would result in an 'Ambiguous mapping methods found' error. A qualifier is a custom annotation and can be placed on a hand written mapper class or a method.

      Note that defaultValue() usage will also be converted using this qualifier.

      Returns:
      the qualifiers
      See Also:
      Default:
      {}
    • qualifiedByName

      String[] qualifiedByName
      String-based form of qualifiers; When looking for a suitable mapping method for a given property, MapStruct will only consider those methods carrying directly or indirectly (i.e. on the class-level) a Named annotation for each of the specified qualifier names.

      Note that annotation-based qualifiers are generally preferable as they allow more easily to find references and are safe for refactorings, but name-based qualifiers can be a less verbose alternative when requiring a large number of qualifiers as no custom annotation types are needed.

      Note that defaultValue() usage will also be converted using this qualifier.

      Returns:
      One or more qualifier name(s)
      See Also:
      Default:
      {}
    • conditionQualifiedBy

      Class<? extends Annotation>[] conditionQualifiedBy
      A qualifier can be specified to aid the selection process of a suitable presence check method. This is useful in case multiple presence check methods qualify and thus would result in an 'Ambiguous presence check methods found' error. A qualifier is a custom annotation and can be placed on a hand written mapper class or a method. This is similar to the qualifiedBy(), but it is only applied for Condition methods.
      Returns:
      the qualifiers
      Since:
      1.5
      See Also:
      Default:
      {}
    • conditionQualifiedByName

      String[] conditionQualifiedByName
      String-based form of qualifiers for condition / presence check methods; When looking for a suitable presence check method for a given property, MapStruct will only consider those methods carrying directly or indirectly (i.e. on the class-level) a Named annotation for each of the specified qualifier names. This is similar like qualifiedByName() but it is only applied for Condition methods.

      Note that annotation-based qualifiers are generally preferable as they allow more easily to find references and are safe for refactorings, but name-based qualifiers can be a less verbose alternative when requiring a large number of qualifiers as no custom annotation types are needed.

      Returns:
      One or more qualifier name(s)
      Since:
      1.5
      See Also:
      Default:
      {}
    • conditionExpression

      String conditionExpression
      A conditionExpression String based on which the specified property is to be checked whether it is present or not.

      Currently, Java is the only supported "expression language" and expressions must be given in form of Java expressions using the following format: java(<EXPRESSION>). For instance the mapping:

      
       @Mapping(
           target = "someProp",
           conditionExpression = "java(s.getAge() < 18)"
       )
       

      will cause the following target property assignment to be generated:

      
           if (s.getAge() < 18) {
               targetBean.setSomeProp( s.getSomeProp() );
           }
       

      Any types referenced in expressions must be given via their fully-qualified name. Alternatively, types can be imported via Mapper.imports().

      This attribute can not be used together with expression() or constant().

      Returns:
      An expression specifying a condition check for the designated property
      Since:
      1.5
      Default:
      ""
    • resultType

      Class<?> resultType
      Specifies the result type of the mapping method to be used in case multiple mapping methods qualify.
      Returns:
      the resultType to select
      Default:
      void.class
    • dependsOn

      String[] dependsOn
      One or more properties of the result type on which the mapped property depends. The generated method implementation will invoke the setters of the result type ordered so that the given dependency relationship(s) are satisfied. Useful in case one property setter depends on the state of another property of the result type.

      An error will be raised in case a cycle in the dependency relationships is detected.

      Returns:
      the dependencies of the mapped property
      Default:
      {}
    • defaultValue

      String defaultValue
      In case the source property is null, the provided default String value is set.

      When the designated target property is of type:

      1. primitive or boxed (e.g. java.lang.Long).

        MapStruct checks whether the primitive can be assigned as valid literal to the primitive or boxed type.

        • If possible, MapStruct assigns as literal.
        • If not possible, MapStruct will try to apply a user defined mapping method.
      2. other

        MapStruct handles the constant as String. The value will be converted by applying a matching method, type conversion method or built-in conversion.

      This attribute can not be used together with constant(), expression() or defaultExpression().

      Returns:
      Default value to set in case the source property is null.
      Default:
      ""
    • nullValueCheckStrategy

      NullValueCheckStrategy nullValueCheckStrategy
      Determines when to include a null check on the source property value of a bean mapping. Can be overridden by the one on MapperConfig, Mapper or BeanMapping.
      Returns:
      strategy how to do null checking
      Since:
      1.3
      Default:
      ON_IMPLICIT_CONVERSION
    • nullValuePropertyMappingStrategy

      NullValuePropertyMappingStrategy nullValuePropertyMappingStrategy
      The strategy to be applied when the source property is null or not present. If no strategy is configured, the strategy given via MapperConfig.nullValuePropertyMappingStrategy(), BeanMapping.nullValuePropertyMappingStrategy() or Mapper.nullValuePropertyMappingStrategy() will be applied. NullValuePropertyMappingStrategy.SET_TO_NULL will be used by default.
      Returns:
      The strategy to be applied when null is passed as source property value or the source property is not present.
      Since:
      1.3
      Default:
      SET_TO_NULL
    • mappingControl

      Class<? extends Annotation> mappingControl
      Allows detailed control over the mapping process.
      Returns:
      the mapping control
      Since:
      1.4
      See Also:
      Default:
      org.mapstruct.control.MappingControl.class