Mapping DTO to Entity on Spring Boot APIs

Mapping DTO to Entity on Spring Boot APIs


What is DTO?

Java entities are nothing but simply represent the persistent model of an application and they are always internal to the application.

However, when we talk about the Dto, it is known as Data Transfer Objects and it exposes the model that our application exposes with the outside application and world.

As a better programming practice, we do not expose our internal persistence entities to the outside world. It simply means that the Data transfer object always interacts with the controller layer and our repository or persistence layer interacts with the actual entities.

It simply means the service layer should do the conversion between DTO and entities.


DTOs and Spring Boot APIs

Another benefit of employing DTOs in Java (and Spring Boot) RESTful APIs is that they can help hide implementation details of domain objects (aka. entities). If we don't carefully manage which attributes can be altered by which activities, exposing entities through endpoints can become a security risk.


ModelMapper 

To avoid having to write boilerplate code to map DTOs into entities and vice-versa, we are going to use a library called ModelMapper. The goal of ModelMapper is to make object mapping easy by automatically determining how one object model maps to another. 


Let's say we have a Admin like this:



By using ModelMapper we would have to create a DTO like this:


And then call ModelMapper as follows:



Post a Comment

0 Comments