• MapStruct making access address: https://github.com/mapstruct/mapstruct/

  • Example: github.com/mapstruct/m…

  • MapStrcut compares with other tools and uses instructions! www.tuicool.com/articles/ui…

  • Whether beanutils.copyProperties has been used for object property copies. All sorts of hiccups have cropped up.

    • Copies properties of the same name to another object, which is easy to do but has a disadvantage (slow)
    • Some fields with the same name that cannot be specialized will result in fields that you do not want to modify being overwritten. You also cannot customize property mappings
  • At the MVC level we often have DTO objects returned to the front end for field rendering. We don’t like to show all the fields to the front end, or we need to change the fields back to the front end, such as the data stored on and off shelves is 0,1 but the front end needs true and false. We all have to do manual judgment processing and edit it into dtos and send it back to the front end

MapStruct is a type-safe Bean mapping class that generates Java annotation processors. All we need to do is define a mapper interface that declares any necessary mapping methods. During compilation, MapStruct generates an implementation of this interface. The implementation uses a mapping between source and target objects called by pure Java methods, MapStruct saves time by generating code to complete tedious and error-prone code logic.

  • Advantages of MapStruct:

    • Using a normal method call instead of reflection to execute quickly, he copies the value from the source to the target directly through a simple getter/setter call instead of reflection or similar when the compiler generates the corresponding Impl method call
    • Compile-time type safety: Only objects and attributes can be mapped to each other, and no accidental mapping of commodity entities to user Dtos, etc
    • Clear error reports at build time, such as incomplete mapping (not all target attributes are mapped) or incorrect mapping (unable to find appropriate mapping methods or type conversions)
  • Important notes provided by MapStruct:

    • Mapper: Marks this interface as a mapping interface and an entry point to the MapStruct processor at compile time
    • @mapping: Resolve the problem that the attribute names of the source object and target object are different
    • The implementation of the interface automatically generated by Mappers. GetMapper is available through Mapper’s class object, giving clients access to the implementation of the Mapper interface
<? The XML version = "1.0" encoding = "utf-8"? > < project XMLNS = "http://maven.apache.org/POM/4.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd" > < properties > / /... < org. Mapstruct. Version > 1.2.0. Final < / org. Mapstruct. Version > < / properties > < dependencies >... <! -- MapStruct START --> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-jdk8</artifactId> <version>${org.mapstruct.version}</version> </dependency> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>${org.mapstruct.version}</version> </dependency> <! -- MapStruct END --> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> < artifactId > maven -- the compiler plugin < / artifactId > < version > 3.5.1 track of < / version > < configuration > < source > 1.8 < / source > < target > 1.8 < / target > < annotationProcessorPaths > < path > < groupId > org. Mapstruct < / groupId > <artifactId>mapstruct-processor</artifactId> <version>${org.mapstruct.version}</version> </path> </annotationProcessorPaths> <compilerArgs> <compilerArg>-Amapstruct.defaultComponentModel=spring</compilerArg> <compilerArg>-Amapstruct.suppressGeneratorTimestamp=true</compilerArg> <compilerArg>-Amapstruct.suppressGeneratorVersionInfoComment=true</compilerArg> </compilerArgs> </configuration> </plugin> </plugins> </build> </project>Copy the code
  • The BasicObjectMapper contains four basic methods, singleton and collection and reversed singleton and collection. In the development of such as the need for object conversion operation can be directly new interface and inherit BasicObjectMapper, and add @mapper (componentModel = “Spring “) on the new interface, If the attribute contains another class and the class already exists in Mapper, add users = {class name.class} to the annotation. ComponentModel = “Spring” This configuration means that the generated implementation class has the spring @Component annotation by default, which can be injected directly with @Autowire when used
public interface BasicObjectMapper<SOURCE, TARGET> {

 
    @Mappings({})

    @InheritConfiguration

    TARGET to(SOURCE var1);

 
    @InheritConfiguration

    List<TARGET> to(List<SOURCE> var1);

 
    @InheritInverseConfiguration

    SOURCE from(TARGET var1);

 
    @InheritInverseConfiguration

    List<SOURCE> from(List<TARGET> var1);

 
}

Copy the code
  • Direct use for object data conversion
@data public class ProductCategory {/** categoryCode */ private String categoryCode; /** categoryName */ private String categoryName; } @Data public class CategoryVo { private String code; private String name; } import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.Mappings; import org.mapstruct.factory.Mappers; @Mapper public interface CategoryMapper extends BasicObjectMapper<CategoryVo, ProductCategory> { CategoryMapper MAPPER = Mappers.getMapper(CategoryMapper.class); @Mappings({ @Mapping(source = "code", target = "categoryCode"), @Mapping(source = "name", target = "categoryName") }) ProductCategory to(CategoryVo source); } public static void main(String[] args) { CategoryMapper categoryMapper = CategoryMapper.MAPPER; CategoryVo vo = new CategoryVo(); vo.setCode("0000"); Vo.setname (" Attribute name "); ProductCategory pc = categoryMapper.to(vo); Println ("1" + PC); // ProductCategory System.out.println("1" + PC); CategoryVo vo1 = categoryMapper.from(pc); Println ("2" + vo1); // Get CategoryVo from system.out.println ("2" + vo1); List<ProductCategory> pcList = categoryMapper.to(Arrays.asList(vo, vo1)); Println ("3" + pcList); system.out.println ("3" + pcList); List<CategoryVo> voList = categoryMapper.from(pcList); Println ("4" + voList); // Set system.out.println ("4" + voList); }Copy the code
  • Custom methods added to the mapper: In some cases, you need to manually implement a specific mapping from one type to another that MapStruct cannot generate. There are two ways to do this:
  • Method 1> implement this method on another class and then use it by a MapStruct generated MapStruct
  • Approach 2> In Java 8 or later, you can implement custom methods directly in the mapper interface as the default. If the arguments match the return type, the generated code calls the default method
@Mapper public interface CarMapper { CarMapper MAPPER = Mappers.getMapper(CarMapper.class); @Mappings({... }) CarDto carToCarDto(Car car); default PersonDto personToPersonDto(Person person) { // hand-written mapping logic } }Copy the code
  • A mapper can also be defined as an abstract class rather than an interface and implement custom methods directly in this mapper class. In this case, MapStruct will generate an extension of the abstract class and implement all the abstract methods. The advantage of this approach over declaring the default is that you can declare additional fields in the mapper class
@Mapper

public abstract class CarMapper {

    @Mappings(...)

    public abstract CarDto carToCarDto(Car car);

 

    public PersonDto personToPersonDto(Person person) {

        // hand-written mapping logic

    }

}
Copy the code
  • Multiple source parameter mapping methods: MapStruct supports multiple source parameter mapping methods, combining several entities into a single data transfer object
@Mapper

public interface AddressMapper {

    @Mappings({

        @Mapping(source = "person.description", target = "description"),

        @Mapping(source = "address.houseNo", target = "houseNumber")

    })

    DeliveryAddressDto personAndAddressToDeliveryAddressDto(Person person, Address address);

}
Copy the code
  • If multiple source objects define a property with the same name, the @mapping annotation must be used to specify the source parameter from which the property is retrieved, and if this ambiguity is not resolved, an error will be raised. For properties that exist only once in a given source object, specifying the name of the source parameter is optional because it can be determined automatically
@mapper public interface AddressMapper {@mappings ({@mapping (source = "person.description", target = "description"), @Mapping(source = "hn", target = "houseNumber") }) DeliveryAddressDto personAndAddressToDeliveryAddressDto(Person person, Integer hn); }Copy the code
  • Direct field access mapping: MapStruct supports mapping of fields that public does not have getters/setters, and MapStruct will use these fields as read/write accessors if MapStruct cannot find suitable getter/setter methods for properties. If it is public, the field is said to be read accessor public Final. If a field static is not considered a read accessor, it is only considered public if the field is considered a write visitor. If a field is final and/or static it is not considered a write visitor
public class Customer { private Long id; private String name; // getters and setter omitted for brevity } public class CustomerDto { public Long id; public String customerName; } @Mapper public interface CustomerMapper { CustomerMapper MAPPER = Mappers.getMapper( CustomerMapper.class ); @Mapping(source = "customerName", target = "name") Customer toCustomer(CustomerDto customerDto); @InheritInverseConfiguration CustomerDto fromCustomer(Customer customer); } public class CustomerMapperImpl implements CustomerMapper {@override public Customer toCustomer(CustomerDto customerDto) { // ... customer.setId( customerDto.id ); customer.setName( customerDto.customerName ); / /... } @Override public CustomerDto fromCustomer(Customer customer) { // ... customerDto.id = customer.getId(); customerDto.customerName = customer.getName(); / /... }}Copy the code
  • Retrieve Mapper: Mapper instance by org. Mapstruct. Factory. The Mappers getMapper () method to retrieve. Normally the mapper interface should define a member INSTANCE named, which contains a single INSTANCE of the mapper type:
@Mapper public interface CarMapper { CarMapper INSTANCE = Mappers.getMapper(CarMapper.class); CarDto carToCarDto(Car car); } This pattern makes it very easy for customers to use mapper objects without repeatedly instantiating new instances: Car Car =... ; CarDto dto = CarMapper.INSTANCE.carToCarDto( car ); Using dependency injection: @mapper (componentModel = "Spring ") public interface CarMapper {CarDto carToCarDto(Car Car); } @Inject private CarMapper mapper;Copy the code
  • Data type conversion: The attribute types mapped in the source object and the target object may be different. MapStruct provides automatic type conversion, providing the following automatic conversion:
    • 1> Java primitive data types and their corresponding wrapper types, such as int and Integer, Boolean and Boolean generated code is a sense when NULL converts a wrapper type to the corresponding primitive type, that is, null checking will be performed
    • 2> Java base number type and wrapper type, such as between int and long or byte and Integer (accuracy loss may occur when converting large class data to small classes)
    • 3> Between all Java primitive types (including their wrappers) and strings, such as int and String or Boolean and String, java.text.decimalFormat can specify format strings
    • Int to String conversion
@mapper public interface CarMapper {@mapping (source = "price", numberFormat = "$#.00") CarDto carToCarDto(Car car); @IterableMapping(numberFormat = "$#.00") List<String> prices(List<Integer> prices); } BigDecimal convert to String @mapper public interface CarMapper {@mapping (source = "power", numberFormat = "#.##E0") CarDto carToCarDto(Car car); @mapper public interface CarMapper {@mapping (source = "manufacturingDate", dateFormat = "dd.MM.yyyy") CarDto carToCarDto(Car car); @IterableMapping(dateFormat = "dd.MM.yyyy") List<String> stringListToDateList(List<Date> dates); Mapper public interface CarMapper {CarDto carToCarDto(Car Car); CarMapper public interface CarMapper {CarDto carToCarDto(Car Car); PersonDto personToPersonDto(Person person); } @mapper public interface FishTankMapper {@mapping (target = "fish.kind", source = "fish.type"), @Mapping(target = "fish.name", ignore = true), @Mapping(target = "plant", ignore = true ), @Mapping(target = "ornament", ignore = true ), @Mapping(target = "material", ignore = true), @Mapping(target = "ornament", source = "interior.ornament"), @Mapping(target = "material.materialType", source = "material"), @Mapping(target = "quality.report.organisation.name", source = "quality.report.organisationName") }) FishTankDto map( FishTank source ); }Copy the code
  • Calling other mappers: Mapping methods defined in other classes can be called in a MapStruct, either by MapStruct generation or by hand
Public class DateMapper {public String asString(Date Date) {return Date! = null ? new SimpleDateFormat("yyyy-MM-dd").format(date) : null; } public Date asDate(String date) { try { return date ! = null ? new SimpleDateFormat("yyyy-MM-dd").parse(date) : null; } catch (ParseException e) { throw new RuntimeException(e); @mapper (uses = datemapper.class) public class CarMapper {CarDto carToCarDto(Car Car); }Copy the code
  • When generating code for the implementation of the carToCarDto() method, MapStruct looks for methods that map Date objects to strings, Find it on the DateMapper class and generate a call to asString() that maps the manufacturingDate property
  • Mapping collections: Collection types (mapping List, Set, and so on) map bean types in the same way by defining mapping methods to the source and target types required in the mapper interface. The generated code will contain a loop that iterates through the source collection, transforming each element and putting it into the target collection. If a mapping method for the collection element type is found in a given mapper or mapper it uses, this method is called to perform the element transformation. Alternatively, this conversion routine is called if there is an implicit conversion between the source and target element types
@Mapper public interface CarMapper { Set<String> integerSetToStringSet(Set<Integer> integers); List<CarDto> carsToCarDtos(List<Car> cars); CarDto carToCarDto(Car car); Override public Set<String> integerSetToStringSet(Set<Integer> integers) {if (Integer == null) {return  null; } Set<String> set = new HashSet<>(); for (Integer integer : integers) { set.add(String.valueOf(integer)); } return set; } @Override public List<CarDto> carsToCarDtos(List<Car> cars) { if (cars == null) { return null; } List<CarDto> list = new ArrayList<>(); for (Car car : cars) { list.add(carToCarDto(car)); } return list; } Map Map: public interface SourceTargetMapper { @MapMapping(valueDateFormat = "dd.MM.yyyy") Map<String, String> longDateMapToStringStringMap(Map<Long, Date> source); } @mapper public interface CarMapper {Set<String> integerStreamToStringSet(Stream<Integer> integers); List<CarDto> carsToCarDtos(Stream<Car> cars); CarDto carToCarDto(Car car); }Copy the code
  • Mapping enumeration: By default, each constant in the source enumeration maps to a constant with the same name in the target enumeration type. If desired, you can use the @valuemapping annotation to help map constants in the Source enum to constants with other names
@Mapper public interface OrderMapper { OrderMapper INSTANCE = Mappers.getMapper(OrderMapper.class); @ValueMappings({ @ValueMapping(source = "EXTRA", target = "SPECIAL"), @ValueMapping(source = "STANDARD", target = "DEFAULT"), @ValueMapping(source = "NORMAL", target = "DEFAULT") }) ExternalOrderType orderTypeToExternalOrderType(OrderType orderType); } Defaults and constants: @Mapper(uses = StringListMapper.class) public interface SourceTargetMapper { SourceTargetMapper INSTANCE = Mappers.getMapper(SourceTargetMapper.class); @Mappings({ @Mapping(target = "stringProperty", source = "stringProp", defaultValue = "undefined"), @Mapping(target = "longProperty", source = "longProp", defaultValue = "-1"), @Mapping(target = "stringConstant", constant = "Constant Value"), @Mapping(target = "integerConstant", constant = "14"), @Mapping(target = "longWrapperConstant", constant = "3001"), @Mapping(target = "dateConstant", dateFormat = "dd-MM-yyyy", constant = "09-01-2014"), @Mapping(target = "stringListConstants", constant = "jack-jill-tom") }) Target sourceToTarget(Source s); } expression: @Mapper public interface SourceTargetMapper { SourceTargetMapper INSTANCE = Mappers.getMapper(SourceTargetMapper.class);  @Mapping(target = "timeAndFormat", expression = "java( new org.sample.TimeAndFormat( s.getTime(), s.getFormat() ) )") Target sourceToTarget(Source s); }Copy the code
  • Determine the result type: When the result type has an inheritance relationship, the choice between the Mapping method (@Mapping) or the factory method (@beanMapping) may become unclear. So let’s say we have an Apple and a banana, and these are both Fruit specialties
@Mapper(uses = FruitFactory.class) public interface FruitMapper { @BeanMapping(resultType = Apple.class) Fruit map(FruitDto source); } public class FruitFactory { public Apple createApple() { return new Apple("Apple"); } public Banana createBanana() { return new Banana("Banana"); }}Copy the code
  • Controls the mapping result of the ’empty’ parameter: By default null will be returned, by specifying nullValueMappingStrategy = nullValueMappingStrategy. @ BeanMapping RETURN_DEFAULT, @ IterableMapping, @mapMapping, or globally @mapper or @mappingConfig, the mapping result can be changed to return an empty default value

    • 1> Bean mapping: Returns an ’empty’ target Bean, which will be populated as it exists, except for constants and expressions
    • 2> primitive: The default value of the primitive will be returned, such as false for Boolean or 0 for int
    • Iterables/Arrays: An empty iterator will be returned
    • 4> Map: This will return a blank map
  • Shared configuration: The possibility of defining shared configuration @mapperConfig by pointing to the central interface. To enable the mapper to use shared configuration, you need to define the configuration interface in the @mapper #config property. The @mapperConfig annotation has the same attribute as the @mapper annotation. Any attribute @mapper that does not pass will inherit from the shared configuration. Attributes that specify @mapper take precedence over those specified through the referenced configuration class

@MapperConfig(uses = CustomMapperViaMapperConfig.class, unmappedTargetPolicy = ReportingPolicy.ERROR)

public interface CentralConfig {}

@Mapper(config = CentralConfig.class, uses = { CustomMapperViaMapper.class } )

public interface SourceTargetMapper {}
Copy the code