MapStruct - Java Mapper

MapStruct is a Java Bean Mapper.

It contains functions that automatically maps between two Java functions. We only need to create the interface, and the library will automatically create a concrete implementation.

Implementation

config

pom.xml modifications for maven

<dependency>
	<groupId>org.mapstruct</groupId>
	<artifactId>mapstruct</artifactId>
	<version>1.3.1.Final</version>
</dependency>

We also need to configure the compiler-plugin to generate the sources on built time.

 <!-- Sets the compiler version -->
<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-compiler-plugin</artifactId>
	<version>${maven.compiler.plugin.version}</version>
	<!-- config for MapStruct -->
	<configuration>
		<source>11</source>
		<target>11</target>
		<annotationProcessorPaths>
			<path>
				<groupId>org.mapstruct</groupId>
				<artifactId>mapstruct-processor</artifactId>
				<version>1.3.0.Beta2</version>
			</path>
		</annotationProcessorPaths>
	</configuration>
</plugin>

code

We have a Person.class

@Data
public class Person {
    private Long id;
    private Integer age;
    private String name;
}

And a PersonDto.class without id

@Data
public class PersonDto {
    private Integer age;
    private String name;
}

In order for MapStruct to work, we need to create a mapper interface, but we don’t need to implement it. The implementation will be created at compile time.

@Mapper
public interface PersonMapper {
    Person personDtoToPerson(PersonDto personDto);
    PersonDto personToPersonDto(Person person);
}

If we do a mvn clean install it will generate a class called PersonMapperImpl.class that contains the generated code.

(lo dejo en 4.4. A Test Case)

Reference(s)

https://www.baeldung.com/mapstruct