Guía rápida de MapStruct

1. Información general

En este artículo, exploraremos el uso de MapStruct, que es, en pocas palabras, un mapeador de Java Bean.

Esta API contiene funciones que se asignan automáticamente entre dos Java Beans. Con MapStruct solo necesitamos crear la interfaz, y la biblioteca creará automáticamente una implementación concreta durante el tiempo de compilación.

2. MapStruct y Transfer Object Pattern

Para la mayoría de las aplicaciones, notará una gran cantidad de código repetitivo que convierte los POJO en otros POJO.

Por ejemplo, ocurre un tipo común de conversión entre entidades respaldadas por persistencia y DTO que van al lado del cliente.

Ese es el problema que resuelve MapStruct : la creación manual de mapeadores de frijoles requiere mucho tiempo. La biblioteca puede generar clases de mapeadores de frijoles automáticamente .

3. Maven

Agreguemos la siguiente dependencia en nuestro pom.xml de Maven :

 org.mapstruct mapstruct 1.3.1.Final 

La última versión estable de Mapstruct y su procesador están disponibles en el repositorio central de Maven.

Agreguemos también la sección annotationProcessorPaths a la parte de configuración del complemento maven-compiler- plugin.

El procesador de mapeo se usa para generar la implementación del mapeador durante la construcción:

 org.apache.maven.plugins maven-compiler-plugin 3.5.1  1.8 1.8   org.mapstruct mapstruct-processor 1.3.1.Final    

4. Mapeo básico

4.1. Creando un POJO

Primero creemos un POJO de Java simple:

public class SimpleSource { private String name; private String description; // getters and setters } public class SimpleDestination { private String name; private String description; // getters and setters }

4.2. La interfaz Mapper

@Mapper public interface SimpleSourceDestinationMapper { SimpleDestination sourceToDestination(SimpleSource source); SimpleSource destinationToSource(SimpleDestination destination); }

Observe que no creamos una clase de implementación para nuestro SimpleSourceDestinationMapper , porque MapStruct lo crea para nosotros.

4.3. El nuevo mapeador

Podemos activar el procesamiento de MapStruct ejecutando una instalación limpia de mvn .

Esto generará la clase de implementación en / target / generate-sources / annotations / .

Aquí está la clase que MapStruct crea automáticamente para nosotros:

public class SimpleSourceDestinationMapperImpl implements SimpleSourceDestinationMapper { @Override public SimpleDestination sourceToDestination(SimpleSource source) { if ( source == null ) { return null; } SimpleDestination simpleDestination = new SimpleDestination(); simpleDestination.setName( source.getName() ); simpleDestination.setDescription( source.getDescription() ); return simpleDestination; } @Override public SimpleSource destinationToSource(SimpleDestination destination){ if ( destination == null ) { return null; } SimpleSource simpleSource = new SimpleSource(); simpleSource.setName( destination.getName() ); simpleSource.setDescription( destination.getDescription() ); return simpleSource; } }

4.4. Un caso de prueba

Finalmente, con todo lo generado, escribamos un caso de prueba que mostrará que los valores en SimpleSource coinciden con los valores en SimpleDestination .

public class SimpleSourceDestinationMapperIntegrationTest { private SimpleSourceDestinationMapper mapper = Mappers.getMapper(SimpleSourceDestinationMapper.class); @Test public void givenSourceToDestination_whenMaps_thenCorrect() { SimpleSource simpleSource = new SimpleSource(); simpleSource.setName("SourceName"); simpleSource.setDescription("SourceDescription"); SimpleDestination destination = mapper.sourceToDestination(simpleSource); assertEquals(simpleSource.getName(), destination.getName()); assertEquals(simpleSource.getDescription(), destination.getDescription()); } @Test public void givenDestinationToSource_whenMaps_thenCorrect() { SimpleDestination destination = new SimpleDestination(); destination.setName("DestinationName"); destination.setDescription("DestinationDescription"); SimpleSource source = mapper.destinationToSource(destination); assertEquals(destination.getName(), source.getName()); assertEquals(destination.getDescription(), source.getDescription()); } }

5. Mapeo con inyección de dependencia

A continuación, obtengamos una instancia de un asignador en MapStruct simplemente llamando a Mappers.getMapper (YourClass.class).

Por supuesto, esa es una forma muy manual de obtener la instancia; una alternativa mucho mejor sería inyectar el asignador directamente donde lo necesitamos (si nuestro proyecto usa alguna solución de inyección de dependencia).

Afortunadamente, MapStruct tiene un soporte sólido tanto para Spring como para CDI ( Contexts and Dependency Injection ).

Para usar Spring IoC en nuestro mapeador, necesitamos agregar el atributo componentModel a @Mapper con el valor spring y para CDI sería cdi .

5.1. Modificar el asignador

Agregue el siguiente código a SimpleSourceDestinationMapper :

@Mapper(componentModel = "spring") public interface SimpleSourceDestinationMapper

6. Asignación de campos con diferentes nombres de campo

De nuestro ejemplo anterior, MapStruct pudo mapear nuestros beans automáticamente porque tienen los mismos nombres de campo. Entonces, ¿qué pasa si un bean que estamos a punto de mapear tiene un nombre de campo diferente?

Para nuestro ejemplo, crearemos un nuevo bean llamado Employee y EmployeeDTO .

6.1. Nuevos POJO

public class EmployeeDTO { private int employeeId; private String employeeName; // getters and setters }
public class Employee { private int id; private String name; // getters and setters }

6.2. La interfaz Mapper

Al mapear diferentes nombres de campo, necesitaremos configurar su campo de origen a su campo de destino y para ello necesitaremos agregar la anotación @Mappings . Esta anotación acepta una matriz de anotaciones @Mapping que usaremos para agregar el atributo de origen y destino.

En MapStruct también podemos usar la notación de puntos para definir un miembro de un bean:

@Mapper public interface EmployeeMapper { @Mappings({ @Mapping(target="employeeId", source="entity.id"), @Mapping(target="employeeName", source="entity.name") }) EmployeeDTO employeeToEmployeeDTO(Employee entity); @Mappings({ @Mapping(target="id", source="dto.employeeId"), @Mapping(target="name", source="dto.employeeName") }) Employee employeeDTOtoEmployee(EmployeeDTO dto); }

6.3. El caso de prueba

Nuevamente, debemos probar que los valores de los objetos de origen y destino coincidan:

@Test public void givenEmployeeDTOwithDiffNametoEmployee_whenMaps_thenCorrect() { EmployeeDTO dto = new EmployeeDTO(); dto.setEmployeeId(1); dto.setEmployeeName("John"); Employee entity = mapper.employeeDTOtoEmployee(dto); assertEquals(dto.getEmployeeId(), entity.getId()); assertEquals(dto.getEmployeeName(), entity.getName()); }

Se pueden encontrar más casos de prueba en el proyecto Github.

7. Mapeo de frijoles con frijoles secundarios

A continuación, mostraremos cómo mapear un bean con referencias a otros beans.

7.1. Modificar el POJO

Agreguemos una nueva referencia de bean al objeto Employee :

public class EmployeeDTO { private int employeeId; private String employeeName; private DivisionDTO division; // getters and setters omitted }
public class Employee { private int id; private String name; private Division division; // getters and setters omitted }
public class Division { private int id; private String name; // default constructor, getters and setters omitted }

7.2. Modificar el asignador

Here we need to add a method to convert the Division to DivisionDTO and vice versa; if MapStruct detects that the object type needs to be converted and the method to convert exists in the same class, then it will use it automatically.

Let’s add this to the mapper:

DivisionDTO divisionToDivisionDTO(Division entity); Division divisionDTOtoDivision(DivisionDTO dto);

7.3. Modify the Test Case

Let’s modify and add a few test cases to the existing one:

@Test public void givenEmpDTONestedMappingToEmp_whenMaps_thenCorrect() { EmployeeDTO dto = new EmployeeDTO(); dto.setDivision(new DivisionDTO(1, "Division1")); Employee entity = mapper.employeeDTOtoEmployee(dto); assertEquals(dto.getDivision().getId(), entity.getDivision().getId()); assertEquals(dto.getDivision().getName(), entity.getDivision().getName()); }

8. Mapping With Type Conversion

MapStruct also offers a couple of ready-made implicit type conversions, and for our example, we will try to convert a String date to an actual Date object.

For more details on implicit type conversion, you may read the MapStruct reference guide.

8.1. Modify the Beans

Add a start date for our employee:

public class Employee { // other fields private Date startDt; // getters and setters }
public class EmployeeDTO { // other fields private String employeeStartDt; // getters and setters }

8.2. Modify the Mapper

Modify the mapper and provide the dateFormat for our start date:

@Mappings({ @Mapping(target="employeeId", source = "entity.id"), @Mapping(target="employeeName", source = "entity.name"), @Mapping(target="employeeStartDt", source = "entity.startDt", dateFormat = "dd-MM-yyyy HH:mm:ss")}) EmployeeDTO employeeToEmployeeDTO(Employee entity); @Mappings({ @Mapping(target="id", source="dto.employeeId"), @Mapping(target="name", source="dto.employeeName"), @Mapping(target="startDt", source="dto.employeeStartDt", dateFormat="dd-MM-yyyy HH:mm:ss")}) Employee employeeDTOtoEmployee(EmployeeDTO dto);

8.3. Modify the Test Case

Let’s add a few more test case to verify the conversion is correct:

private static final String DATE_FORMAT = "dd-MM-yyyy HH:mm:ss"; @Test public void givenEmpStartDtMappingToEmpDTO_whenMaps_thenCorrect() throws ParseException { Employee entity = new Employee(); entity.setStartDt(new Date()); EmployeeDTO dto = mapper.employeeToEmployeeDTO(entity); SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT); assertEquals(format.parse(dto.getEmployeeStartDt()).toString(), entity.getStartDt().toString()); } @Test public void givenEmpDTOStartDtMappingToEmp_whenMaps_thenCorrect() throws ParseException { EmployeeDTO dto = new EmployeeDTO(); dto.setEmployeeStartDt("01-04-2016 01:00:00"); Employee entity = mapper.employeeDTOtoEmployee(dto); SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT); assertEquals(format.parse(dto.getEmployeeStartDt()).toString(), entity.getStartDt().toString()); }

9. Mapping With an Abstract Class

Sometimes, we may want to customize our mapper in a way which exceeds @Mapping capabilities.

For example, in addition to type conversion, we may want to transform the values in some way as in our example below.

In such case, we can create an abstract class and implement methods we want to have customized and leave abstract those, that should be generated by MapStruct.

9.1. Basic Model

In this example, we'll use the following class:

public class Transaction { private Long id; private String uuid = UUID.randomUUID().toString(); private BigDecimal total; //standard getters }

and a matching DTO:

public class TransactionDTO { private String uuid; private Long totalInCents; // standard getters and setters }

The tricky part here is converting the BigDecimaltotalamount of dollars into a Long totalInCents.

9.2. Defining a Mapper

We can achieve this by creating our Mapper as an abstract class:

@Mapper abstract class TransactionMapper { public TransactionDTO toTransactionDTO(Transaction transaction) { TransactionDTO transactionDTO = new TransactionDTO(); transactionDTO.setUuid(transaction.getUuid()); transactionDTO.setTotalInCents(transaction.getTotal() .multiply(new BigDecimal("100")).longValue()); return transactionDTO; } public abstract List toTransactionDTO( Collection transactions); }

Here, we've implemented our fully customized mapping method for a single object conversion.

On the other hand, we left the method which is meant to map Collectionto a Listabstract, so MapStruct will implement it for us.

9.3. Generated Result

As we have already implemented the method to map single Transactioninto a TransactionDTO, we expect Mapstructto use it in the second method. The following will be generated:

@Generated class TransactionMapperImpl extends TransactionMapper { @Override public List toTransactionDTO(Collection transactions) { if ( transactions == null ) { return null; } List list = new ArrayList(); for ( Transaction transaction : transactions ) { list.add( toTransactionDTO( transaction ) ); } return list; } }

As we can see in line 12, MapStruct uses our implementation in the method, that it generated.

10. Before-mapping and After-mapping Annotations

Here's another way of customizing @Mapping capabilities by using @BeforeMapping and @AfterMapping annotations. The annotations are used to mark methods that are invoked right before and after the mapping logic.

They are quite useful in scenarios where we might want this behavior to be applied to all mapped super-types.

Let's take a look at an example that maps the sub-types of Car; ElectricCar, and BioDieselCar, to CarDTO.

While mapping we would like to map the notion of types to the FuelType enum field in the DTO, and after the mapping is done we'd like to change the name of the DTO to uppercase.

10.1. Basic Model

In this example, we’ll use the following classes:

public class Car { private int id; private String name; }

Sub-types of Car:

public class BioDieselCar extends Car { }
public class ElectricCar extends Car { }

The CarDTO with an enum field type FuelType:

public class CarDTO { private int id; private String name; private FuelType fuelType; }
public enum FuelType { ELECTRIC, BIO_DIESEL }

10.2. Defining the Mapper

Now let's proceed and write our abstract mapper class, that maps Car to CarDTO:

@Mapper public abstract class CarsMapper { @BeforeMapping protected void enrichDTOWithFuelType(Car car, @MappingTarget CarDTO carDto) { if (car instanceof ElectricCar) { carDto.setFuelType(FuelType.ELECTRIC); } if (car instanceof BioDieselCar) { carDto.setFuelType(FuelType.BIO_DIESEL); } } @AfterMapping protected void convertNameToUpperCase(@MappingTarget CarDTO carDto) { carDto.setName(carDto.getName().toUpperCase()); } public abstract CarDTO toCarDto(Car car); }

@MappingTarget is a parameter annotation that populates the target mapping DTO right before the mapping logic is executedin case of @BeforeMapping and right after in case of @AfterMapping annotated method.

10.3. Result

The CarsMapper defined above generatestheimplementation:

@Generated public class CarsMapperImpl extends CarsMapper { @Override public CarDTO toCarDto(Car car) { if (car == null) { return null; } CarDTO carDTO = new CarDTO(); enrichDTOWithFuelType(car, carDTO); carDTO.setId(car.getId()); carDTO.setName(car.getName()); convertNameToUpperCase(carDTO); return carDTO; } }

Notice how the annotated methods invocations surround the mapping logic in the implementation.

11. Support for Lombok

In the recent version of MapStruct, Lombok support was announced. So we can easily map a source entity and a destination using Lombok.

To enable Lombok support we need to add the dependency in the annotation processor path. So now we have the mapstruct-processor as well as Lombok in the Maven compiler plugin:

 org.apache.maven.plugins maven-compiler-plugin 3.5.1  1.8 1.8   org.mapstruct mapstruct-processor 1.3.1.Final   org.projectlombok lombok 1.18.4    

Let's define the source entity using Lombok annotations:

@Getter @Setter public class Car { private int id; private String name; }

And the destination data transfer object:

@Getter @Setter public class CarDTO { private int id; private String name; }

The mapper interface for this remains similar to our previous example:

@Mapper public interface CarMapper { CarMapper INSTANCE = Mappers.getMapper(CarMapper.class); CarDTO carToCarDTO(Car car); }

12. Support for defaultExpression

Starting with version 1.3.0, we can use the defaultExpression attribute of the @Mapping annotation to specify an expression that determines the value of the destination field if the source field is null. This is in addition to the existing defaultValue attribute functionality.

The source entity:

public class Person { private int id; private String name; }

The destination data transfer object:

public class PersonDTO { private int id; private String name; }

Si el campo id de la entidad de origen es nulo, queremos generar un id aleatorio y asignarlo al destino manteniendo los otros valores de propiedad como están:

@Mapper public interface PersonMapper { PersonMapper INSTANCE = Mappers.getMapper(PersonMapper.class); @Mapping(target = "id", source = "person.id", defaultExpression = "java(java.util.UUID.randomUUID().toString())") PersonDTO personToPersonDTO(Person person); }

Agreguemos un caso de prueba para verificar la ejecución de la expresión:

@Test public void givenPersonEntitytoPersonWithExpression_whenMaps_thenCorrect() Person entity = new Person(); entity.setName("Micheal"); PersonDTO personDto = PersonMapper.INSTANCE.personToPersonDTO(entity); assertNull(entity.getId()); assertNotNull(personDto.getId()); assertEquals(personDto.getName(), entity.getName()); }

13. Conclusión

Este artículo proporcionó una introducción a MapStruct. Hemos introducido la mayoría de los conceptos básicos de la biblioteca de mapas y cómo usarla en nuestras aplicaciones.

La implementación de estos ejemplos y pruebas se puede encontrar en el proyecto Github. Este es un proyecto de Maven, por lo que debería ser fácil de importar y ejecutar tal como está.