1, the principle of

A class file of set/get code is dynamically generated at compile time and called directly at run time. * This method actually throws the set/get code, but you don’t need to write it yourself

2. Use mode

2.1. Introduce dependencies

   <properties>
        <org.mapstruct.version>1.3.1. The Final</org.mapstruct.version>
    </properties>
        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct-processor</artifactId>
            <version>${org.mapstruct.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct-jdk8</artifactId>
            <version>${org.mapstruct.version}</version>
        </dependency>
Copy the code

2.2. Static use

public interface ItemInfoConvert { 
// Static methodItemInfoConvert INSTANCE = Mappers.getMapper(ItemInfoConvert.class); } call: the Person the Person = ItemInfoConvert. INSTANCE. DeliveryDO2DTO (cart);Copy the code

2.3 Spring Container Injection (recommended)

// Use @mapper (componentModel = "spring")
@Mapper(componentModel = "spring") public interface ItemInfoConvert {}; Call:// Direct interface injection, method call
 @Autowired  private ItemInfoConvert itemInfoConvert;  
Person person = itemInfoConvert.deliveryDO2DTO(cart); 

Copy the code

3, extension,

Mainly through a variety of annotations to achieve bean mapping of some conversion operations, such as inconsistent field names, inconsistent data types and other problems are as follows:

@Mappings({
            // Ignore the categoryId conversion
            @Mapping(target = "categoryId",ignore = true),
            // Collection application in source data class --> data reference in target class -- transform List
            @Mapping(target = "trees",source = "colors"),
            // The attributes of the nested class simply pass the conversion
            @Mapping(target = "run",source = "cart.animal.run"),
           //numberFormat Format Number type --> Number or String or String or Number; Other cases are invalid.
            / / the string - > Double: *. 0 (12.0); The effective length is 16 bits more accurate.
            //string -->Float: single precision, valid length of 8 bits, if beyond the number after the probability of victory; 12.00033452 or 12.00033456 will be converted to 12.00033452
            @Mapping(target = "numberPerson", source = "cart.number", numberFormat = "0.00", defaultValue = "0"),
            // Opportunities for use are rarely unexplained
            @Mapping(target = "birthday", source = "birthDateFormat", dateFormat = "yyyy-MM-dd HH:mm:ss"),
    })
    Person deliveryDO2DTO(Cart cart);
    
Copy the code

3. Examples

Here is the code generated by compilation, clean-compile each time an interface is updated