A concise guide to MapStruct, a Java framework for efficient object mapping. This guide compares MapStruct with ModelMapper, shows SOLID principles in practice, and highlights key annotations.
MapStruct generates type-safe mapping code at compile-time, avoiding reflection, and making object mapping fast, reliable, and easy to maintain.
| Feature | MapStruct | ModelMapper |
|---|---|---|
| How it works | Compile-time code generation | Runtime reflection to map fields |
| Performance | High, optimized pre-generated code | Lower, reflection adds runtime overhead |
| Ease of maintenance | Clear annotations, easy to debug | Flexible but less intuitive, errors at runtime |
- Single Responsibility Principle (SRP): Each mapper class has a single responsibility — mapping objects.
- Open/Closed Principle (OCP): Mappers can be extended/configured via annotations without changing existing code.
- Dependency Inversion Principle (DIP):
@Mapperenables dependency injection, easing testing and extension.
| Annotation | Description |
|---|---|
| @Mapper | Declares a MapStruct mapper interface |
| @Mapping | Defines mapping rules between source and target fields |
| @MappingTarget | Updates an existing object instead of creating a new one |
| @AfterMapping | Defines a post-processing method to run after mapping |
| @BeforeMapping | Defines a method to execute before mapping |
| @ValueMapping | Maps values between enums |