Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC architecture DTO/Model mapping/conversion

Using Spring MVC we normally see Controller, Service and Repository layer. The Repository layer uses Entity model which is one to one mapping with database. I thought of following -

  1. Should Service layer use the same Entity model?
  2. Should Service layer use separate Domain model? If yes then the to/fro mapping should be done in Service layer?
  3. Should Controller layer we use the same Domain model?
  4. Should Controller layer use separate DTO model? If yes then the to/fro mapping should be done in Controller layer?
  5. Do we have any simple way to do mapping without writing too much verbose code? I have used Dozer few times in the past.

This question may have been asked but I could not find. So excuse me for duplicate question.

like image 915
Bhushan Bhangale Avatar asked Jan 25 '16 08:01

Bhushan Bhangale


1 Answers

The entity model used throughout the service layer should be the same. Depending on your architecture and complexity of your application you might want to use different domain models in the service and the controller layer. My recommendation is:

  • Services always work on the Entities which are retrieved and stored using the database
  • Services always take DTOs or simple types as parameters and return only DTOs. Why? Because the DTOs are detached from the database and you neither run into LazyInitializationException nor will you have to use the open-session-in-view anti-pattern.
  • Think of the DTOs as the only model shared between Services and Controllers
  • For the mapping between the Entity and the DTO objects I recommend to use ModelProjector. It is very simple, lean and leaves a minimal footprint

ModelProjector simple maps one model into the other by matching the property names. If they do not match, you can tell it with annotation It is also possible to map complex entity hierarchies onto "flattened" data structures with very straight-forward annotations. The Entity classes remain untouched.

like image 194
user10269 Avatar answered Oct 03 '22 00:10

user10269