Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put Entity To DTO transformation in a Spring boot project?

I'm working on a spring boot (MVC, DATA, JPA...) + angular project.

I'm stuck between two options. Although, they both work without any problems.

It's just from an Architecture viewpoint which one is the best or which one is used most.

My question is where's the best way to do the transformation from Entity to DTO.

Option 1 : The one I'm implementing now.

I put the transformation in the controller. In my controller I call a service method to get a list of entities. And then, I do the transformation of a list of entities to a list of DTOs using a ModelMapper and return the result to the front.

Entity ==> Repository ==> Service ==> Controller ==> ModelMapper ==> Return DTO
  • Pros : Service Layer will always return entities objects (reuse)

  • Cons : A lot of code in the controller (in case I need to parse the list...)

Option 2 :

Put the transformation in the service layer.

So, instead of returning a list of entities, my service layer will return a list of DTOs.

Entity ==> Repository ==> Service ==> ModelMapper ==> Controller  ==> Return DTO
  • Pros : Objects returned by the service will be returned directly to the front (not a lot of code in controller)

  • Cons : I dont know ^^'

like image 554
Mehdi Ayari Avatar asked Nov 14 '19 14:11

Mehdi Ayari


2 Answers

Following the clean coding principles, Service layer should do the conversion, but as it is conversion only and no business logic is involved, your controller can also do that. However I would do that in controller only, if conversion code isn't more than 3-4 lines of code. As it would make my controller look cluttered with code. Reference- https://www.baeldung.com/entity-to-and-from-dto-for-a-java-spring-application.

like image 57
Caffeine Coder Avatar answered Oct 02 '22 22:10

Caffeine Coder


I believe better way of converting entity to DTO would be :

  • If you don't really need entity in service, then convert entity to
    DTO on repository level only. Also if you're using Spring Data JPA,
    then you can directly convert entity to DTO without any extra code.
    But if you're writing your complex queries which can not be fulfilled by it, then you can convert it inside your repo implementation.
    Doing this will ensure that no services will ever get hold of data
    which it must not have. No sensitive data will be exposed.

  • If you really need entity and there's no work around for it, then
    you can convert it to DTO in service layer as controller must never
    have data access which it should not. No sensitive data should ever
    be exposed to controller level. It's not a good design.

I think these are ways you can do conversion of entity to DTO, but the best design is to convert entity to DTO in repo itself.

I hope this helps you solve your problem.

Good luck!

like image 29
semicolon Avatar answered Oct 03 '22 00:10

semicolon