Getting started with MapStruct

Amit Verma
Xebia Engineering Blog
2 min readJun 15, 2020

Why did MapStruct come into picture?

MapStruct is a library that takes away a lot of boilerplate code for mapping between POJO’s. With MapStruct there is no need for implementing the real mapping. The mappings between different data models often arise in enterprise applications, for instance when portraying data from an internal domain model to the UI layer or external services. This becomes quite an unpleasant task for developers. Writing mapping code by hand is tedious and error-prone while reflection-based solutions like iterating over all the properties and copy them between source and target objects are promising. There are some downsides to it as well like lack of type safety and performance penalties associated with it.

Why MapStruct?

MapStruct solves all the above mentioned issues and generates mapping code at compile time, based on Java Interface definitions. Resulting mappings are type-safe and super fast because plain methods are called without any dependencies which are easy to understand.

Some of the key feature are:

- Type-safe
- Quick feedback loop
- Easy to debug
- Plain method calls
- No run time dependencies
- Works on CLI or on your IDE

Let’s take an example for better understanding.

Gradle build file

Make some changes to the build.gradle file to include the dependencies for MapStruct and Lombok.

Domain Class

As domain we create a class Customer.

Customer Dto Class

This is the class that we have to map from Customer .

MapStruct Mapper

Now we can create our CustomerMapper interface with the mandatory MapStruct annotations which is nothing but a Java Interface.

Now build the project and have a look at the implementation of CustomerMapper.

It’s probably located in

./build/generated/sources/annotationProcessor/java/main

Cool, We were able to propagate the data of Customer to CustomerDto.

The implementation of these examples and tests can be found in the GitHub project. This is a Gradle project, so it should be easy to import and run as it is.

--

--