Conceptual question: DTO vs. Entity (JPA)

I am struggling with a conceptual question about using DTOs.

I have a project with about 100 entities. So far I didn’t use any DTO, and I have seen around in some project such RentYourStuff the use of DTOs. However I don’t get the idea. Creating 100 DTOs and use Spring repositories for each would blow up the code.

Can someone explain the rational about such design? Eventually provide some concrete use-cases of DTOs.

Creating 100 JPA entities, then 100 DTOs, 100 data repositories and 100 mappers is what people usually do when developing applications with pure Spring Boot and React/Angular/etc.
The goal of this tedious work is to provide a presentation data model separate from the persistence model. This approach has its pros and cons and the balance shifts depending on the application requirements.

If your application displays and works with data mostly in the same structure as they are stored in the database, the persistence and presentation models will be almost identical. So there is little sense in separating them. This is the default scenario in Jmix - you define only the persistence model in JPA entities and they are directly used by your UI.

But if you need to display some data in a structure different from the database (which is defined by tables and JPA entities), you can create a DTO and map your persistent data to it using any custom logic. This way you can extend your data model with entities not directly mapped to the database.

Another use case for DTOs in Jmix is defining a model of data coming from some arbitrary storage, e.g. an external API. You can find examples of working with such data in the jmix-samples-2/external-data-sample project.

Regards,
Konstantin

2 Likes

Thanks Konstantin for the clear and comprehensive explanation.

So far I built my application without using DTOs, with entities graph hierarchies it is possible to do so without the need to create specific DTOs for the presentation layer.

I have the situation where I need to create new frontend using Flutter with a different presentation requirements than the backoffice Flowui interface. In this case, I am planning to rely on the REST api plugin and eventually here DTOs might be of some support.

Are there any considerations I have to be aware of?

In this case I’d suggest writing standard Spring MVC controllers that expose regular POJOs for your frontend. The Jmix Generic REST is great for exposing the data model as it is in persistence, but it cannot help for a custom model.