[Awesome-Java MapStruct] Using MapStruct to generate mapping code between Java bean types on Spring Boot
MapStruct
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.
MapStruct is an annotation processor which is plugged into the Java compiler and can be used in command-line builds (Maven, Gradle etc.) as well as from within your preferred IDE.
MapStruct uses sensible defaults but steps out of your way when it comes to configuring or implementing special behavior.
Installation
Gradle
When using a modern version of Gradle (>= 4.6), you add something along the following lines to your build.gradle:
1 | dependencies { |
Apache Maven
If you’re using Maven to build your project add the following to your pom.xml to use MapStruct:
1 | <properties> |
Usages
PO and DTO
Let’s assume we have a class representing cars (e.g. a JPA entity) and an accompanying data transfer object (DTO).
1 | public class Car { |
1 | public class CarDto { |
The mapper interface
To generate a mapper for creating a CarDto object out of a Car object, a mapper interface needs to be defined:
1 | import org.mapstruct.Mapper; |
We can trigger the MapStruct processing by executing an mvn clean install.
This will generate the implementation class under /target/generated-sources/annotations/
.
Using the mapper
Based on the mapper interface, clients can perform object mappings in a very easy and type-safe manner:
1 |
|
IDE Support
IntelliJ IDEA
Depending on how you configured the annotation processor in your Maven or Gradle project, IntelliJ may or may not pick it up automatically. You might need to make sure of it yourself in the project configuration.
There is an IntelliJ plugin for MapStruct support, that you can find in the Jetbrains plugins repository here MapStruct Support - IntelliJ IDEA & Android Studio Plugin | Marketplace - https://plugins.jetbrains.com/plugin/10036-mapstruct-support. The plugin is open source and you can report bugs and feature requests here on GitHub.
References
[1] MapStruct – Java bean mappings, the easy way! - https://mapstruct.org/
[2] Installation – MapStruct - https://mapstruct.org/documentation/installation/
[3] Reference Guide – MapStruct - https://mapstruct.org/documentation/reference-guide/
[5] Quick Guide to MapStruct | Baeldung - https://www.baeldung.com/mapstruct