Mapstruct – A traditional task on modern way @ Spring part-1 

Introduction 

As microservices and distributed applications quickly taking over the development world – data integrity and security are more important than ever. A secure communication channel and limited data transfer between these loosely coupled systems are paramount. Most of the time, the end-user or service doesn’t need to access the entirety of the data from a model, but only some specific parts. 

Data Transfer Objects (DTOs) are regularly (Used)applied in these applications. DTOs are just objects that hold the requested information of another object. Typically, the information is limited in scope. Since DTOs are a reflection of the original objects -mappers between these classes play a key role in the conversion process. 

If you’ve ever worked with complex object-oriented codebases in Java, you know how time-consuming it can be to write code to map one object to another 

As a java developer, we all have heard about Object Mapper a object mapping library. it is used for Pojo to DTO data mapping or vise-versa. 

But then we are getting complex mapping requirements for complex business logic, we need to find better option for bean mapping. 

There are so many libraries for bean mapping for object mapping in java. 

what are other options available for java object mapping in JAVA? 

  • Dozer  
  • Orica  
  • MapStruct  
  • ModelMapper  
  • JMapper 

but today we are going to talking about Mapstruct 

What is MapStruct? 

  •  MapStruct is an open-source project that was first released in 2012. It is licensed under the Apache License 2.0 and is actively maintained by a team of contributors. The project is hosted on GitHub and has a large community of users and contributors. 
  •  MapStruct is designed to be easy to use, even for developers who are new to the tool. To get started, you need to define a set of mappings between the source and target Java classes. MapStruct uses these mappings to generate the code that performs the actual mapping. 
  • MapStruct is a Java-based code generator which creates code for mapping implementations and simplifies the process of mapping one Java object to another.  
  • The generated mapping code uses plain method invocations and thus is fast, type-safe and easy to understand.  
  • It uses annotation-processing to generate mapper class implementations during compilation and greatly reduces the amount of boilerplate code which would regularly be written by hand.  
  • It generates type-safe mapping code for you, which saves you the time and effort of writing the code yourself.  
  • This makes it a popular tool among Java developers who work with complex object-oriented codebases. 

Why MapStruct ? 

  • 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.  
  • In contrast to other mapping frameworks MapStruct generates bean mappings at compile-time which ensures a high performance, allows for fast developer feedback and thorough error checking. 

Benefits of Mapstruct 

  • Reduces boilerplate code: MapStruct generates mapping code automatically, eliminating the need for writing repetitive mapping code by hand. This saves time and reduces the risk of introducing bugs. 
  •  Type-safe: MapStruct generates type-safe mapping code at compile time, which helps catch mapping errors early in the development process. 
  • Highly customizable: MapStruct provides a wide range of configuration options, allowing you to customize the generated mapping code to meet specific needs. You can configure things such as method names, mapping behavior, and type conversions. 
  • Fast performance: MapStruct generates highly optimized mapping code, resulting in faster mapping performance compared to other mapping frameworks. 
  • Easy to use: MapStruct is easy to learn and use, with a straightforward mapping syntax and intuitive configuration options. You don’t need to be an expert in mapping frameworks to get started with MapStruct. 
  • Supports a wide range of mapping scenarios: MapStruct supports mapping between objects with matching or different property names, and between objects with different types, including collections and arrays. 
  • Integration with popular IDEs: MapStruct has plugins for popular IDEs such as Eclipse, IntelliJ, and NetBeans, making it easy to integrate into your development workflow. 

Drawback of mapstruct 

  • Learning curve: While MapStruct is generally easy to learn, there is still a learning curve involved. Developers may need to invest time in understanding the annotation-based mapping syntax and the configuration options available. 
  • Configuration complexity: While MapStruct offers a high degree of customization, this can also lead to complexity in configuring the mapping process. Developers may need to spend time experimenting with the various options to achieve the desired mapping behavior. 
  • Limited support for complex mapping scenarios: While MapStruct supports many common mapping scenarios, it may not be the best choice for more complex scenarios. For example, mapping between objects with circular dependencies can be challenging with MapStruct. 
  • Potential performance overhead: While MapStruct generates highly optimized mapping code, there may still be some performance overhead involved in the mapping process. In some cases, manual mapping may be faster than using MapStruct-generated code. 
  • Limitations with third-party libraries: MapStruct may not work well with some third-party libraries or frameworks, particularly those that rely on dynamic proxies or bytecode manipulation. 

Get start with Mapstruct 

To get started with MapStruct, you’ll need to add it as a dependency to your project. The easiest way to do this is to add it to your project’s build file, such as pom.xml if you’re using Maven or build.gradle if you’re using Gradle. Here’s an example of how you can add MapStruct to a Maven project: 

Here is dependency which we need to add: 

Here is plugin which we need to add: 

Once you’ve added the MapStruct dependency and plugin to your project, you can start using it to generate mapping code. To do this, you’ll need to define a mapper interface that specifies how to map one class to another. You can use annotations such as @Mapper and @Mapping  to define the mapping rules. 

Here’s an example of Used and UserDto classes: 

and now we are defining how you could use MapStruct to map a User object to a UserDto object: 

In this example, we’ve defined a mapper interface called UserMapper and marked it with the @Mapper annotation. We’ve also defined a mapping method called userToUserDto, which takes a User object as input and returns a UserDto object. 

The @Mapping annotation is used to specify how individual fields should be mapped. In this example, we’ve mapped the firstName field of the User object to the fullName field of the UserDto object, and we’ve specified a custom date format for the createdAt field using the dateFormat parameter. 

Once you’ve defined the mapper interface, you can use it to generate the mapping code by running a build command. For example, if you’re using Maven, you can run the mvn clean install command to generate the code. 

and below i have shared what magic has been done by mapstruct to implement mapper: 

I hope this example helps illustrate how you could use MapStruct in your own Java projects! 

What’s Next? 

In the next article (in progress…), we’ll look into deep dive into Mapstruct with complex example. 

Thanks  

Uday Halpara 

Software Engineer @ Prama 

Author
Latest Blogs

SEND US YOUR RESUME

Apply Now