Spring DTO-DAO (Resource - entity) mapping goes in which application layer: Controller or Service?

Tiksi picture Tiksi · Jul 27, 2015 · Viewed 12.5k times · Source

I'm writing a Spring (4.1.7) web application that exposes a RESTful service and wish to use DTO "resource" objects for communication between Controller and client browser rather than expose my persistence entities.

Currently the application has the following layers:

  • View (JSP/JSON)
  • Controller(s)
  • DAO (@Service)
  • DAO (@Repository)

My question is, where should I be mapping my DAO entities to DTO resources? I had a look at some examples using Spring HATEOAS and they show Resource objects extending ResourceSupport being mapped in the Controller. Is this the best way to do it, or should I be returning resources from the DAO Service?

I wish to add Link elements to the returned resource (for self and related resources), but can't see how Link elements would be resolved if processed in the Service without it having knowledge of the Controller and it's @RequestMapping. On the other hand, I don't know if it's good practice to clutter the Controller with the mapping either.

Answer

Morteza Adi picture Morteza Adi · Jul 27, 2015

DTO ( Data Transfer Object) as obvious in its name, is used for transfering data out of your application. In your case the best place to put them is in your controller layer. You should only expose DTO's to UI and when you get a data from UI you should convert it to the business entity and call the below tier. The reason is, in this way you are free to change the business entitiy without breaking UI and leads to better maintenance. Also your business/DAO tier should be unaware of UI and DTO's for the same reason. So the best place to convert DTO to Business Entities and vice versa in your app is Controller tier.

PS:Take a look at Dozer too ;)