How to convert Entity classes to DTO classes in Java (Map / Cast / Parse)

Tech Tips 🤖
2 min readJul 12, 2021

In the developer’s daily life, we often need to convert entity classes to classes in the DTO standard, and vice versa, to do some kind of treatment with specific fields or meet a need for an application layer. With that, we basically make calls in the GET and SET methods of the objects to fill them, thus becoming very verbose and with repetitive code our control and service classes.

To meet this need, some frameworks have emerged with the proposal of converting these objects in a simple way, through a simple mapping, among them the simplest in my opinion is MapStruct. See the example below:

Entity Car
DTO class of Car
An interface that mapping the class Car
And finally, the test class that check if mapping works

Below I demonstrate with a simple example the use of the framework in a maven project, with the following dependencies:

  • mapstruct:1.4.2.Final
  • mapstruct-processor:1.4.2.Final
  • assertj-core:3.6.2
  • junit4-runner:5.0.0-ALPHA

See the implementation below:

Check the source code here on GitHub.

By Marcio Gadelha | Software Engineer www.linkedin.com/in/marciogadelha

--

--

Tech Tips 🤖

We want to be a contribution and communication channel in technology for professionals and those interest.