Search code examples
javaspringmodelentitydto

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.


Solution

    1. Yes.
    2. No. The service should work on the Entity model returned by the Repository object.
    3. No. The Controller should use DTO. The DTO should contain the form fields and the Validation annotations (if you are using JSR303).
    4. Yes. DTOs are used in the Controller layer. DTOs should expose a constructor that accepts Entity model. The conversion of Entity model into DTO is done in this constructor. Same case for the Entity model. Entity model should also expose an overloaded constructor that accepts DTO object as argument. Conversion of DTO to Entity model should happen here.
    5. The overloaded constructor of DTO (Entity model as arg) and Entity model (DTO as arg) are verbose.