Home » Framework » Conversion between Entity to DTO using ModelMapper

Conversion between Entity to DTO using ModelMapper

In this article, we are going to see how to use DTO in Spring Boot. DTO (Data Transfer Object) is used to transfer one object into another object. Here I used Spring Boot with ModelMapper set up to explain how this conversion happens.

Before going to the setup let me explain why we need this type of conversion in the project. While sending data to UI we don't want to send all the fields of record right.

For this, we have to create the new class with needed fields and transfer the fields from the Pojo that we are fetching and return that to the UI. So doing like this is a big process right. We can avoid this by using ModelMapper DTO.

Actually, ModelMapper DTO also does the same process but only the difference is ModelMapper transfers the fields from one object to another automatically. We can also hide the fields to transfer with DTO. Now we start to see how to implement this.

Setup ModelMapper in Spring Boot

The entity is a class that binds with the database table and DTO is also an object or class which will have the copy of Entity values.

There are many mechanisms for converting DTO to Entity and vise versa. But here I used ModelMapper and Fasterxml to achieve this. So please include the below dependencies in your pom.xml file.

<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.3.6</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>

You can use the latest version of both ModelMapper and Fasterxml. Now the setup is ready we can start to integrate. Before that, if you are seeing the error like below in the console while running the project then you have to do the ModelMapper bean declaration in the main class of Spring Boot.

Error: "Field modelMapper in org.filos.controller.CartController required a bean of type 'org.modelmapper.ModelMapper'

ModelMapper Declartion Error

@Bean declaration in Main Class of Spring Boot.

@SpringBootApplication
@Configuration
public class WorkApplication {
    @Bean
    public ModelMapper modelMapper() {
        ModelMapper modelMapper = new ModelMapper();
        return modelMapper;
    }
    public static void main(String[] args) {
        SpringApplication.run(WorkApplication.class, args);
    }
}

Here I used ProfileEntity and ProfileDTO classes to explain the conversion. First, we will see Entity to DTO conversion. This type of conversion converts the field values from entity to DTO and returns them to the client. This conversion is only used for fetching data from DB.

ProfileEntity.java

import java.util.Date;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "profile")
public class ProfileEntity {
    @Id
    private String _id;
    private String firstName;
    private String lastName;
    private String userId;

    //Audit fields
    private String createdBy;
    private Date createdOn;

    //Getters and Setters here
}

ProfileDTO.java

import java.util.Date;

public class ProfileDTO {
    private String _id;
    private String firstName;
    private String lastName;
    private String userId;

    //Audit fields
    private String createdBy;
    private Date createdOn;

    //Getters and Setters Here
}

The below snippet is used for converting Entity to DTO.

@Autowired
private static ModelMapper modelMapper;

//Function to convert Entity to DTO
private static ProfileDTO convertEntityToDTO(ProfileEntity profileEntity) {
    ProfileDTO profileDTO = modelMapper.map(profileEntity, ProfileDTO.class);
    return profileDTO;
}

The above function returns the DTO with all the fields of ProfileEntity. There may be a situation you don't want to fetch and return some fields to UI. In this case, fasterxml is the right choice for that.

In the above example if you don't want to show the audit fields to UI then please do the following changes in ProfileDTO. We can use the @JsonProperty class from fasterxml to achieve this.

Just put this line above the field which you don't want to fetch @JsonProperty(access = Access.WRITE_ONLY).

For example changes with ProfileDTO class.

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonProperty.Access;
public class ProfileDTO {
    private String _id;
    private String firstName;
    private String lastName;
    private String userId;

    //Audit fields
    @JsonProperty(access = Access.WRITE_ONLY)
    private String createdBy;
    @JsonProperty(access = Access.WRITE_ONLY)
    private Date createdOn;
    //getters and setters
}

Fasterxml is a good Java-based library that is used to serialize Java objects to JSON and vise versa. Like @JsonProperty annotation, fasterxml is having many annotations @JsonSerialize, @JsonCreator, @JsonAnySetter, @JsonSetter, @JsonProperty, @JsonIgnore and etc...

You can use any of these in your project as per your requirements.

I hope you understood the conversion of Entity to DTO with ModelMapper. In the next article, we will see conversion between DTO to Entity.

Leave a Reply

Your email address will not be published. Required fields are marked *