Introduction to DTO Pattern

Need for DTO Pattern

With the entity classes, we are supporting inside our web application to create new account, new customer details, to fetch the account and customer details, to update and delete these details.

What if one of the client application, where they want both your accounts and customer data together in a single request??? 

Do you think we can send two different objects as a response? Of course not. We cannot send them two different objects.

We can only send a single object from inside a response. Maybe you can think like we can create one more entity or pojo class, and inside them I can try to create the fields of accounts and customer. That way I can embed both these two classes inside another class.

That’s one of the basic approaches, but we should not do that. The reason is all these entity classes, they are related to the database layer. You may end up in various scenarios where you may want to send the data in various formats or in various combinations.

→ That’s why we should never touch these database related entity classes. They should always clearly and purely represent the database tables.

So to overcome this challenge, we have a standard with the name DTO pattern.

What is the DTO Pattern ?

DTO stands for Data Transfer Object.

What the pattern says is, whenever a client is trying to communicate with a backend application to get the data, we should follow the DTO pattern, which is a design pattern that will allow to transfer data between different parts of your application.

For example, inside my application I can have a database layer, presentation layer service layer. So to flow the data between multiple layers of your web application, we should use these DTO pattern and inside this DTO pattern, we should create the DTO classes which holds the fields that you want to transfer to and fro from the different layers of your application.

Q) On the right hand side, I have a Customer entity class and an Accounts entity class. Some client, may request you to send both the customer and accounts data in a single request.

A) Solution – In such scenarios, what you can do is, create a DTO class with the name like CustomerDetails. And inside this DTO class you can define all the fields that your client is asking from these entity classes.

Once you define a class in between, you can write a mapper logic or aggregation logic that will take care of converting all your field values from DB entity to DTO class.

This way my client applications who are using web applications like with the help of HTML page or who are trying to invoke my rest APIs with the help of other backend APIs. They can always request whatever data that they want from my database tables.

Think of a scenario, if you don’t have this DTO pattern and if your UI application or if another client API, they’re trying to ask you, provide me both customer and accounts table data.

So in that case you will ask them to send the two different requests, one for customer and the other one for accounts, which is unnecessary. Whereas with the DTO pattern they will make a single request and you will have a mapper logic which will take care of combining the data from the customer and accounts and transferring it to the CustomerDetails class. And the same you will be responding back to the client applications.

These DTO classes usually represent only the data that they carry. We are not supposed to write any other business logic inside these DTO classes. Apart from these data fields, we can also write logic related to the serialization.

When I say serialization, some clients may ask you to send the data as an XML or as an JSON format or an YAML format. So whatever serialization format that they need, you can always write that logic inside your DTO class.

With the help of this DTO pattern, your presentation layer is going to be decoupled from the data access layer. What is the meaning of decoupling between the presentation layer and the data access layer?

This means your presentation layer, like your client applications, never knows what database entities, what is the fields that they hold, what kind of data that they hold. They don’t have to worry.

And if there is anything changing inside the database entities, that will never impact the client applications because client applications always work with the help of DTO class.

As a next step, what we have to do is, for each of the DB entities that we have created inside our web application, we need to create a corresponding DTO class so that we can send that data or response to the client applications when they invoke our REST APIs or microservices with the help of DTO pattern and DTO classes that we are going to create.

Creating DTO classes

Entity DTO classes

Let us now create the DTO classes representing each of the entity classes (Customer, Account) that we have inside our accounts microservice.

Create a new package, named dto. Create AccountsDto class.

@Data
@NoArgsConstructor
@AllArgsConstructor
public class AccountsDto {
private Long accountNumber;
private String accountType;
private String branchAddress;
}

@Data annotation

This annotation is a combination of – 

We didn’t want to use @Data annotation on top entity classes, because we don’t want equals(), hashCode() methods inside my entity classes. Sometimes, it is going to create issues with the Spring Data JPA framework.

@Data
@NoArgsConstructor
@AllArgsConstructor
public class CustomerDto {
private String name;
private String email;
private String mobileNumber;
}

Response DTO classes

I want to create two more DTOs that will help me to send the response to the client application in certain scenarios.

@Data
@AllArgsConstructor
public class ResponseDto {
private String statusCode;
private String statusMsg;
}

With these two fields we are going to send what is the status code and status message inside the response. Using which my client can easily understand whether the given operation is successful or not.

@Data
@AllArgsConstructor
public class ErrorResponseDto {
private String apiPath;
private HttpStatus errorCode;
private String errorMessage;
private LocalDateTime errorTime;
}

apiPath – this represents what is the API path that my client application is trying to invoke.

I want to send inside the ErrorResponseDto that you invoke this path and it failed due to so and so error code and the error message and so & so error time.

I’m going to send the error code which is of type HttpStatus to the client applications saying what is the reason that the API invocation failed?

→ So with these 4 fields, my clients will have all the information like which API they tried to invoke, What is the error code that they received, what is the error message and at what time the error happened.

At this time, as of now, we just created DTOs, so there should be some mapper logic that we need to build.

In some organizations, they call these DTO objects as Value objects or Transfer objects. So regardless, the name that they are using, if they are using different POJO classes instead of database Entity POJO classes to transfer the data between multiple layers of the application, then they are following the DTO pattern.