Implementing Mapstruct On Spring Boot

I thought a lot what to write as first article and I decided to write about Mapstruct on spring boot cause I am using frequently at job.

Introduction:

Mapstruct is a code generator and help us to convert 2 different java object depends on our configuration. While we are developing a software, we don’t want to response directly entity objects. it is not safe and useless. Cause of that, we are using mapstruct as a super hero :)

Maven:

First of all we need to add map struct libraries to pom.xml. İt will be inside of dependencies section.

The latest stable release of Mapstruct and his processor are both available from the Maven Central Repository.

Next step is adding annotationProcessorPaths section to the configuration part of maven-compiler-plugin.

A Simple Example:

As we mentioned above, we don’t want to have entity object as response. Lets create a basic ProductEntity class.

This class has basic fields for product. Lets think that we have client project and wanna show product detail. We have requirement price with currency. So that it needed to create ProductOutput.

As you can see productId represented id, price became productPrice as string value. Because of this requirement we need to map ProductEntity to ProductOutput. Mapstruct makes it so easy. Let's create an interface and call it “ProductMapper”.

We created mapProductEntity2Output. We passed the source to this method, it will return the target.

Here, under @ Maps annotaion, we can make definitions for each of our fields, which are different.

What we call qualifiedByName is actually our custom mapping. In our example, we convert the decimal price field to a string type and add our currency next to it.We pass the price field to this method.Parameter name doesn't matter, you can name it any way you want.After doing this, do maven-install by right-clicking on the main directory of the project and click left on run as.When you do this, mapstruct will automatically generate the implementation under generated-sources according to the interface that we defined.

Now we can call method.

I'm not gonna show the controller and service call parts so as not to drown you with more code. The output of this service will be as follows.

Servis cevabı

In this article, I mentioned the use of mapstruct on java spring boot and the creation of a custom method. I hope you feel the benefits of using it in your projects, thank you very much for being patient by reading the whole :)



References:

https://mapstruct.org/

https://www.baeldung.com/mapstruct

You can click here to show full source code.

Share this

Mustafa Baş

Mustafa Baş

Software Developer @Obss
5 yıldır remote/freelance geliştiriciyim ve #java, #.net, #.net, #javascript, #node.js teknolojileri ile çalışmalar yapıyorum. Ayrıca yeni şehirler görmeyi seviyor ve doğada kamp yapmaya bayılıyorum.

Last Reads