MapStruct

MapStruct%20Docs 2088E9?logo=quickLook&logoColor=white MapStruct%20API%20Docs DF7716?logo=devbox&logoColor=white

Overview

MapStruct is a code generator which automates generation of Type Converters. It works like Project Lombok via annotation processing during code compilation. It is useful for creating Type Converters which can convert Data Transfer Object (DTO) into Database Entity and Database Entity into Data Transfer Object (DTO).

Spring Framework has a functional interface: ⚪ Converter<S,T> which has convert(S source) method returning T target type. It is an alternative to MapStruct. See Spring Type Conversion.

Maven Dependency

<dependencies>
  <dependency>
    <groupId>org.mapstruct</groupId>
    <artifactId>mapstruct</artifactId>
    <optional>true</optional>
  </dependency>
</dependencies>
<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <annotationProcessorPaths>
            <path>
              <groupId>org.mapstruct</groupId>
              <artifactId>mapstruct-processor</artifactId>
              <version>${mapstruct.version}</version>
            </path>
            <path>
              <groupId>org.projectlombok</groupId>
              <artifactId>lombok</artifactId>
              <version>${lombok.version}</version>
            </path>
            <path>
              <groupId>org.projectlombok</groupId>
              <artifactId>lombok-mapstruct-binding</artifactId>
              <version>${lombok-mapstruct.version}</version>
            </path>
          </annotationProcessorPaths>
          <compilerArgs>
            <compilerArg>-Amapstruct.defaultComponentModel=spring</compilerArg>
          </compilerArgs>
        </configuration>
    </plugin>
  </plugins>
</build>

Generate Type Converter

@Mapper

Marks an interface or abstract class as a Mapper and activates the generation of an implementation of that type via MapStruct:

@Mapper
public interface CustomerMapper {

    Customer toCustomer(CustomerDTO customerDTO);

    CustomerDTO toCustomerDTO(Customer customer);

}