How to use Mapstruct with Spring Boot
We will learn MapStruct dependency for our Spring Boot applications.
What is it?
MapStruct is a code generator that greatly simplifies the implementation of mappings between Java bean types based on a convention over configuration approach.
The generated mapping code uses plain method invocations and thus is fast, type-safe and easy to understand.
Why?
Multi-layered applications often require to map between different object models (e.g. entities and DTOs). Writing such mapping code is a tedious and error-prone task. MapStruct aims at simplifying this work by automating it as much as possible.
Firstly, we need to add MapStruct dependencies into pom.xml/gradle
You can find new versions of MapStruct -> mvnrepository
We will have 2 examples in this article.
Let’s start with an easy one;
Here we have the User model and Let’s imagine that instead of returning the entire model, you are thinking of returning DTO.
such as;
in this case, we can map from User to UserDTO easily with Mapstruct.
We need to create an interface;
Then we just need to call these methods which we need.
The usage is -> UserMapper.INSTANCE.userToUserDTO(user);
It directly returns without id field.
So, the response will be ->
{
"name": "John Doe",
"email": "john.doe@example.com"
}
Another example is;
You may encounter situations where different models store the same information but use different field names.
For example, you have Order.java model
And you have OrderResponse.java
Let’s imagine to format LocalDate orderDate to String purchaseDate , clientName and customerName are same information.
In this case how we can do it easily?
While using @Mapping annotation, we can define them easily as you see in the OrderMapper.java
We can use this mapper in OrderService;
So the OrderResponse will be;
{
"clientName": "Alice Johnson",
"productName": "Smartphone",
"formattedPrice": "$850.75",
"purchaseDate": "18–11–2024"
}
That’s all, as you see, Mapstruct is easy to use, implement and mapping between models, dtos, and responses.
Github: here
Thank you for reading it!