Entity, domain model and DTO – why so many?

Tram Ho

Today’s article is quite good and is also an important topic in Spring Boot. Specifically, we will find out how data will transform when passing through different layers. And what are the concepts of Entity, Domain model and DTO.

1. General Architecture of Spring Boot

1.1. Source code architecture and data architecture

In the previous sections, we have seen that all Spring Boot applications follow two basic models:

  • MVC model
  • 3 tier model (3 tier)

And so we can combine the complete application with the following structure.

The above diagram is used to organize source code in the program. Thanks to that we are divided into Controllers, Services, Repositories corresponding to layers. However, in terms of organization of the data, the diagram becomes as follows.

This model also includes 3 layers, in which the names of the layers are changed to corresponding elements in Spring Boot.

Accordingly, corresponding to each layer, the data will be in a different form. In other words, each layer should only process certain types of data. Each type of data will have different tasks and purposes. Of course, the code is also divided accordingly.

For example, in the diagram, the Controller should not touch data in the form of domain model or entity , only allowed to receive and return DTO .

1.2. Why must divide multiple data types

Due to following the principle of SoC – separation of concerns – separation of concerns in software design. Specifically, we have broken down the Spring Boot application as follows.

Spring Boot = Presentation layer + Service layer + Data access layer

That is the breakdown of source code according to SoC. However, at a lower level, SoC shows through the first principle of SOLID (Single responsibility), which means that each class should perform only one task.

Therefore, in the past, data had only one form, but there were many layers, each layer behaved differently to the data, so the data performed many tasks. This violates the Single responsibility, so we need to break it down into multiple data types.

Another reason is that if the data has only one form, it will leak (expose) sensitive data. For example, the Facebook friend search function, in fact, just above returns data with only basic info (avatar, name, …). If there is only one type of data, all information will be returned. Although the client only displays the necessary information, the full return can be used by bad guys to steal sensitive info.

Therefore, separating data into separate forms is also a way to increase security for the application.

2. Data types

2.1. Two types of data

According to the above diagram, data in Spring Boot application is divided into two main categories:

  • Public: means to exchange, share with outside via REST API or communicate with other services in microservice. Data is now in the form of DTO.
  • Private: the application’s internal data, the outside should not know. The data now resides in Domain models or Entity.

Data types can have many different names, but in general they still belong to the two parts as above. Therefore, when applying to Spring Boot architecture, we will consider what kind of data is suitable for which layer (section 2.2).

From the two types of public and private above, we have 3 types of data:

  • DTO: are classes that encapsulate data to transfer between client – server or between services in microservice. The purpose of the DTO is to reduce the amount of info you don’t need to move, and also increase security.
  • Domain model: are the classes representing domains, understood as business objects such as Client, Report, Department, … for example. In real application, classes representing calculation results, classes as input parameters for computation services, … are considered domain models .
  • Entity: is also domain model but corresponding to table in DB, can be map to DB. Note that only the entity can represent data in the DB.

Data types have corresponding suffixes, except for entity. For example, the entity User has no suffix, if the domain model is the UserModel , or for DTO it is UserDto , … too.

2.2. Principle of selecting data corresponding to the layer

Well I don’t know how to call it. In short, each layer in the 3-layer model will process, receive, and return data of certain types.

Applying to the 3-layer model in the diagram, we derive the general design principle:

  • Web layer: should only handle DTO , which means that the Controller should only receive and return data as DTO .
  • Service layer: receive DTO (from controller sent) or Domain model (from other internal services). Processed data (can interact with DB), finally returned by the Service Web layer as DTO .
  • Repository layer: only manipulate on Entity , because it is an appropriate object, which can be mapped to DB.

For other Spring Boot components that do not belong to any layer:

  • Custom Repository: this is a layer that does not go through the repository but directly manipulates the database. Therefore, this class behaves like a Service .

2.3. Model mapping

As data passes through different layers, it transforms into different forms. For example, DTO from controller goes to service, it will be map to domain model or entity, then when entering Repository, it is required to become Entity. And the opposite is also true.

Converting between data types, for example DTO to Entity, DTO to domain model, domain model to entity or vice versa, is called model mapping.

Model mapping is often done using a library like ModelMapper (usage will be in the next article). However, the simplest one can write pure copy code as follows.

The above code when used will look like this.

Another simpler way is instead of writing the copy method, then copy in the constructor. Therefore, the convert code will be shorter.

3. Reality like?

When applied in practice, there are many multitudes of situations that occur. Not just follow the pattern.

Controller receives DTO> Service converts DTO into model or entity, then processes> Repository receives Entity into DB

Repository taken from DB to Entity> Service, then processed it into DTO> Controller and returned DTO

But there are other cases such as:

  • Controller does not accept DTO but accepts primitive parameters such as int, float, …
  • Get into a DTO List
  • Returns a List DTO

Therefore, in practice one can make changes to suit the project.

The standard example is the Service will do a mapping to DTO and vice versa, the controller only accepts DTO. But sometimes to reduce the load on the service, this mapping will be done by the controller (though the controller can get bloated, while it is true that the controller must be kept thin – as little code as possible).

But either way, the general rule is that mapping is always done at the edge of code (edge). That means if the mapping in the service, the transformation should always be at the top, or at the end of the method when they are processed.

Also, to reduce the boilerplate code, we often reduce the tightness a bit if not needed. Eg:

  • Sometimes without a domain model , the Service can convert DTO directly to an entity .
  • Services can also return Entity or Model , if they are too simple and contain no sensitive info. At this time, there is no need for DTO, but the controller returns Entity or Model to avoid confusion (although it is against the principle of publicizing these two guys, but should also consider).

There is a lot of controversy about the use of DTO, as an anti pattern. Personally, I do not see that, sometimes DTO is still quite useful, and can be customized to be more suitable and effective.

The article has also been long. Honestly, this is my most laborious lesson, because I have to touch a lot of architecture. Just yesterday, I dragged out the old project to refactor it properly, to better understand the architecture I’m going to present and the possible side effects.

The article has a reference to https://www.petrikainulainen.net/software-development/design/understanding-spring-web-application-architecture-the-classic-way/ that I feel best. In the link above there is also the ending and comment, you can read more.

Well forget if you feel the article is good and useful, please upvote and clip to motivate me. Bye bye

Share the news now

Source : Viblo