Java Entity to DTO – Best Practices and Usage

entityjavajpa

Been trying to come up with a flow for a basic tiered web application, and have been reading conflicting information online. What I'm trying to figure out is if there is an advantage to still using DTO objects from your DAO to Service layer through the use of some sort of mapper.

The basic flow I foresee is as follows:

  1. UI Model / Form –> Controller
  2. Controller converts Model into Domain Object (Entity)
  3. Domain Object –> Service Layer
  4. Domain Object –> DAO
  5. DAO –> Domain Object(s)
  6. Service –> UI
  7. UI converts Domain into UI models

If DTO was followed DAO would pass back a DTO not the Entity. After doing some reading it seems like DTO has become slightly defunct since (at least in Java) entities have become annotated POJOs meaning their memory footprint has become very small.

Is this the case, or should DTOs be used to completely encapsulate the domain objects within the DAO layer, and, if this is the case, what would the service layer pass to the DAO?

Thanks a bunch!

Best Answer

According to me, passing a persistable POJO, like for instance a bean managed by JPA, is not THE good practice.

Why?

I see three main reasons:

  1. Potential issue with lazy collections. http://java.dzone.com/articles/avoid-lazy-jpa-collections
  2. Entity should contain behaviour (in contrary of an Anemic domain model) You may not want to let your UI call some unexpected behavior.
  3. In case of anemic domain model you may not want to expose your model structure to the UI, since every new change to model may break UI.

I prefer letting my service layer convert entities to corresponding DTO in both directions. DAO still returning entity (it's not its job to ensure the conversion).

Related Topic