Codementor Events

Entity to DTO conversion

Published Jan 26, 2022
Entity to DTO conversion

In this post, we will take a dive into entity, DTO amd their conversion using the popular library ModelMapper.

Entity

As per the definition from oracle

An entity is a lightweight persistence domain object. Typically, an entity represents a table in a relational database, and each entity instance corresponds to a row in that table. The primary programming artifact of an entity is the entity class, although entities can use helper classes.

In simplified language, an entity typically represents a database table which system is interested in tracking. In short, entity is nothing but a class mapped to table.
For example: Accounts, employees, departments, etc.

Let us look at a coding representation of an entity. Consider a department class which represents a database table.

@Entity
@Data
@Table
public class Department {

    @Id
    @Column
    @GeneratedValue(strategy = GenerationType.AUTO)
    long id;

    @Column
    String departmentName;

    @Column
    String departmentLevel;

}

DTO

As per the definition from Wikipedia

In the field of programming a data transfer object (DTO) is an object that carries data between processes. The motivation for its use is that communication between processes is usually done resorting to remote interfaces (e.g., web services), where each call is an expensive operation. Because the majority of the cost of each call is related to the round-trip time between the client and the server, one way of reducing the number of calls is to use an object (the DTO) that aggregates the data that would have been transferred by the several calls, but that is served by one call only.

In simple terms, Data transfer object design pattern is a design pattern used to reduce the number of calls with remote interfaces. DTO is an object which carries the data between the processes. Ideally it should not contain any business logic but DTO may contain serialization and deserialization mechanisms.

Let us look at the representation of the DTO. For ease of creating getters/setters we will be using lombok library.

package com.example.demo.dto;

import lombok.Data;

//lombok is used for creating getters/setters
@Data
public class DepartmentDTO {

    long id;

    String departmentName;

}

MODELMAPPER

In simple terms, MODELMAPPER helps us to automate the mapping process of entities to DTOs and vice versa. The library is widely used as it avoids writing boiler plate code for mapping. The main goal of ModelMapper library is to determine the how the one object maps to the other. For more information you can click here.

We will cover this with a simple example, we have a department entity and department DTO, we will try to map them using model mapper.

Let us create a department entity with sample data

//setting sample data to the department entity
Department dept = new Department();
dept.setId(1);
dept.setDepartmentName("HR Services");
dept.setDepartmentLevel("level-3");

Now lets map the entity to DTO.

//using modelmapper library to map the department entity to department DTO
ModelMapper mapper = new ModelMapper();
DepartmentDTO deptDTO = mapper.map(dept, DepartmentDTO.class);

System.out.println(deptDTO);

OUTPUT

DepartmentDTO(id=1, departmentName=HR Services)

Process finished with exit code 0

We can see the value of departmentLevel was not populated in our output because it was not mentioned in our DTO. Hence, it can be concluded the mapping is done perfectly from entity to DTO by ModelMapper library.

How to convert List<Entity> to List<DTO> ?

This can be done by many ways. We will try to cover some of them using ModelMapper.

Let us create the List<Department> using sample data,

List<Department> departmentList = new ArrayList<>();

//setting sample data to the department entity
Department dept1 = new Department();
dept1.setId(1);
dept1.setDepartmentName("HR Services");
dept1.setDepartmentLevel("level-3");

Department dept2 = new Department();
dept2.setId(2);
dept2.setDepartmentName("IT Services");
dept2.setDepartmentLevel("level-1");

// adding departments to the list
departmentList.add(dept1);
departmentList.add(dept2);

1) Using TypeToken

In ModelMapper, the TypeToken is used to map generic parameterized types. For more information you can read here.

Now as we have the list of entity, we will convert it into list of DTO

ModelMapper mapper = new ModelMapper();

List<DepartmentDTO> deptDTO = mapper.map(departmentList, new TypeToken<List<DepartmentDTO>>(){}.getType());

System.out.println(deptDTO);

OUTPUT

[DepartmentDTO(id=1, departmentName=HR Services), DepartmentDTO(id=2, departmentName=IT Services)]

Process finished with exit code 0

2) Using the array way

ModelMapper mapper = new ModelMapper();

List<DepartmentDTO> deptDTO = Arrays.asList(mapper.map(departmentList, DepartmentDTO[].class));

System.out.println(deptDTO);

OUTPUT

[DepartmentDTO(id=1, departmentName=HR Services), DepartmentDTO(id=2, departmentName=IT Services)]

Process finished with exit code 0

Conclusion:

We have seen how easily we can map an object to another using ModelMapper library. Also, we have seen the conversion of List<Entity> to List<DTO> which is mostly a scenario faced while writing critical APIs.

Discover and read more posts from Pritish Deshpande
get started
post commentsBe the first to share your opinion
Show more replies