Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use DTOs & Matpstruct in Angular + Java Project

Ok, I've got a big project and I want to do it right..and I don't even what the norm is.

Problem: I have several entities with relationships that I need to display on the page together. Display the Top 3 Events in a view. Where an Event has relationship to EventInstance, a CancelationPolicy, and to multiple Pricing (deadlines), and Multiple EventNotes (filtered by your registration status)

Possible Solutions: (assume I'm using services/observables to fetch data, and I have all java & angular models, etc)

A) In angular fetch the Event, then fetch the event's Instance, the relevant set of Pricings, Notes, and the CancelationPolicy for each entities own service.

B) Create Java service that returns one custom view-DTO with all the data marshalled together.

C) Use Mapstruct to and create a DTO/Mapping/etc for each Entity and I can call the Event Service ...

..... But, if I do this, won't I need to do DTOs/Mapping for all these entities...and won't I need to do this for every entity that has a relationship to these objects... and then these entities services need to only? return DTOs.. and now it all sounds too complicated especially since I have 30 Entities.. and I've just scared myself away from Mapstruct/DTO world.

what am I missing?

I'm using jhipster (angular 5, Spring Boot, mapstruct, etc) to make it all semi-easy.

like image 368
Lance Avatar asked Aug 21 '26 01:08

Lance


1 Answers

Let's make a bit of order...

Actually, you are not forced to return DTOs, you could just return entities. However I would not encourage this habit because you should always hide your database structure to the external world. So, using DTOs is always a good choice, because you could choose to map only a subset of informations contained in your entities.

So now let's pass to MapStruct. By defaut, MapStruct will map everything in your entity into your DTO and vice-versa without need to specify every single mapping. At the start of your project, you could choose to have similar entity and DTO and then leave MapStruct do the job for you, you will have only to say source and destination of your mapping, and MapStruct via Reflection will build Mappers. And then, after some performance test, you can choose to do some tuning only on the most time consuming mappings.

I know that returning entities can lead to faster delivery, but you could use DTOs to apply better managing to any changes that will affect your entities. Alternatively, you can use Spring Rest Repositories to return entities to your frontend components.

like image 108
Lorelorelore Avatar answered Aug 22 '26 14:08

Lorelorelore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!