Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass DTO to service layer

Is it not bad practice to pass DTO object to service layer?

For now my service layer method look like this:

public save(MyEntity entity);

Mapping values from DTO to business entity (MyEntity) is done on presentation layer

But I want to change method signature to this:

public save(MyEntityDTO dto, String author);

And after it mapping from DTO to business entity will occur on service layer.

EDIT: I want it because I need opened hibernate session when mapping from DTO to business object, so all changes on entity will be automatically flushed.

like image 236
WelcomeTo Avatar asked Nov 20 '13 09:11

WelcomeTo


People also ask

Should I pass DTO to service layer?

Not only you could pass DTO objects to Service Layer, but you should pass DTO objects instead of Business Entities to Service Layer. Your service should receive DTOs, map them to business entities and send them to the repository.

Should services use DTOs?

Should we always use DTOs for communication with service layer? Yes, you have to return DTO by your service layer as you have talk to your repository in service layer with domain model members and map them to DTO and return to the MVC controller and vice versa.

How do you convert DTO to entity?

Using Model Mapper Library Thus, we can use model mapper to convert entity to dto or dto to entities. First, we need to add model mapper dependency. Next, we can create a @Bean factory method to create ModelMapper instance. This way, the model mapper instance will be available for injection on the application level.


1 Answers

Is it not bad practice to pass DTO object to service layer?

Not only you could pass DTO objects to Service Layer, but you should pass DTO objects instead of Business Entities to Service Layer.

Your service should receive DTOs, map them to business entities and send them to the repository. It should also retrieve business entities from the repository, map them to DTOs and return the DTOs as reponses. So your business entities never get out from the business layer, only the DTOs do.

See the full answer to a similar question here.

like image 85
Lightman Avatar answered Oct 03 '22 23:10

Lightman