How to Use MapStruct with Lombok’s Builder
AjilAnto | Nov 02 2022Are you still leaving your office late at night or stuck on an existing project by spending valuable time writing boilerplate codes for bean mapping in your powerful multi-layered architecture application? Now, it is time for you to master a new magic spell, which can help you reduce the time that is being wasted by writing many boilerplate codes for bean mapping. Let me introduce MapStruct,Apowerful annotation processor provided by Java. Which helps you to reduce the amount of extra boilerplate code for bean mapping.As of now, MapStruct version 1.5.2 final is the very latest version, which was released on June 18, 2022. It is possible to integrate it with the Lombok Builder pattern for better performance.
Generator Libraries Required
● Lombok isAutomatic Resource Management, automatic generation of getters, setters, equals, hash Code and to String, and more.
● MapStruct is a code generator that greatly simplifies the implementation of mappings between Java bean types based on a convention over configuration approach. These simple snippets of code will make you aware of how these two libraries work hand in hand in the way MapStruct implements Lombok’s builder methods. Implementing the Lombok builder

which will help us to make our code bug-free and maintenance-free.And which will increase the overall quality of the code by reducing unwanted lines of code.
Step 1: If you are using the maven project, make these necessary changes in the pom.xml.
If you are using the Gradle project make changes in the build. Gradle.
Step 2: After making changes in properties, we need to add a couple of dependencies.



Working
ToAchieve MapStruct functionality, we need to create an Interface, which will act as a bridge between the POJOs consisting of @mapper annotation. (@mapper: this annotation tells the MapStruct to generate an implementation class for the given interface).
Consider an example, where we create an entity named as ProductDetails and a ProductResponseDTO and we want to map the fields between them. Compared to other mapping frameworks, MapStruct provides us with the following benefits.

1. Instead of reflection MapStruct provides fast execution by using plain method invocations.

2. This provides compile-time type safety The objects and attributes which share mapping can only be mapped using a MapStruct.
3. MapStruct provides clear build-time reports if any occurred while the time of compiling.
ProductDetails.java
ProductResponseDTO.java
To achieve mapping between the fields in both java classes we need to create an interface that has been mentioned above that consists of @mapper annotation.And we specify the input and the output.
