/DemoMapStruct

Simple examples of MapStruct power

Primary LanguageJava

  • Is not dead
  • Solve type conversion DTOs to Entity and vice versa
  • The library can generate bean mapper classes automatically
  • Support Lombok

Pros

  • Annotation based
  • Easy Configurable
  • Source generated
  • Null safe
  • Compile type Safe

Cons

  • Autogenerated sources

Topics

  • Map only defined fields: @BeanMapping(ignoreByDefault = true)
  • Easy to start: @Mapper
  • Easy to use: org.mapstruct.factory.Mappers.getMapper(Class)
  • Field mapping: @Mapping(target="employeeId", source = "entity.id")
  • Date Pattern: @Mapping(target="employeeStartDt", source = "entity.startDt", dateFormat = "dd-MM-yyyy HH:mm:ss")})
  • Customize flow: @BeforeMapping and @AfterMapping
  • Java expressions: @Mapping(target = "id", source = "person.id", defaultExpression = "java(java.util.UUID.randomUUID().toString())")
  • Enum support: @ValueMapping(source = "DEBIT_CARD_CODE", target = "EXTERNAL_DEBIT_CARD_CODE")
  • Custom Mapper with Method:
@Named("inchToCentimeter") 
public static double inchToCentimeter(int inch) { 
    return inch * 2.54; 
}
@Mapping(source = "inch", target = "centimeter", qualifiedByName = "inchToCentimeter")
  • Custom Mapper with Annotation:
@Qualifier
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.CLASS)
public @interface PoundToKilogramMapper {
}
@PoundToKilogramMapper
public static double poundToKilogram(int pound) {
    return pound * 0.4535;
}
@Mapping(source = "pound", target = "kilogram", qualifiedBy = PoundToKilogramMapper.class)
  • Spring support: @Mapper(componentModel = "spring")