An Entity to DTO

What Is DTO?

Let’s start with the definition of DTO. According to Martin Fowler, DTO is: “An object that carries data between processes in order to reduce the number of method calls. When you're working with a remote interface, such as Remote Facade, each call to it is expensive. As a result, you need to reduce the number of calls... The solution is to create a Data Transfer Object that can hold all the data for the call.”
So, initially, DTOs were intended to be used as a container for remote calls. In a perfect world, DTOs should not have any logic inside and be immutable. We use them only as state holders. Nowadays, many developers create DTOs to transfer data between application layers, even for in-app method calls. If we use JPA as a persistence layer, we can read an opinion that it is a bad practice to use entities in the business logic, and all entities should be immediately replaced by DTOs.

We recently introduced DTO support in the JPA Buddy plugin. The plugin can create DTOs based on JPA entities produced by data access layer classes and vice versa – create entities based on POJOs. This allowed us to look at DTOs closer and see how we can use them on different occasions. For the sake of simplicity, we assume that we use Spring Data JPA to persist data and Spring Framework as the main framework in all our examples.

CategoriesUncategorizedTags