MapStruct is a Java-based code generation library that simplifies the mapping between Java bean types. It generates mapping code at compile-time, reducing the need for boilerplate code and improving maintainability. In this tutorial, we’ll explore the basics of MapStruct with examples.
Installation
To get started with MapStruct, you need to include the MapStruct dependencies in your project. If you are using Maven, add the following to your pom.xml
:
<dependencies>
<!-- MapStruct dependencies -->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.4.2.Final</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.4.2.Final</version>
<scope>provided</scope>
</dependency>
</dependencies>
For Gradle:
dependencies {
// MapStruct dependencies
implementation 'org.mapstruct:mapstruct:1.4.2.Final'
annotationProcessor 'org.mapstruct:mapstruct-processor:1.4.2.Final'
}
Basic Mapping
Example 1: Simple Mapping
Let’s create a simple mapping between two classes.
Now, create a mapper interface.
In this example:
@Mapper
annotation declares the interface as a MapStruct mapper.@Mapping
annotations define how fields are mapped between the source and target classes.
Example 2: Using Component Model
MapStruct supports different component models like Spring, CDI, and more. Here’s an example using the Spring component model.
Advanced Mapping
Example 3: Custom Mappings
You can provide custom methods for mapping complex objects.
In this example, mapAge
is a custom method for mapping the age
field.
Example 4: Iterable Mappings
MapStruct can handle mappings between collections.
Using MapStruct in your Application
Now that you have defined your mappers, you can use them in your application.
Conclusion
MapStruct is a powerful tool for simplifying object mappings in your Java applications. By leveraging code generation, it reduces boilerplate code and improves the maintainability of your codebase. This tutorial covered the basics of setting up MapStruct, creating simple and advanced mappings, and integrating MapStruct into your application. Feel free to explore more advanced features and configurations based on your specific use cases.