To be honest, the Data Transfer Object pattern is not my favourite one. I like to keep my code DRY and the idea of replicating parts of the domain model does not appeal to me. However, exposing entities directly to clients can be tricky, mostly due to their relational nature. Lazily loaded relationships and lengthy object graphs can soon became an issue. Also, more often than not, different clients have different views on the same data and making your core business logic client-agnostic is probably the last thing you want to do. DTO to the rescue, as it provides a good control over the data volume and shape.

For the sake of performance and maintainability, the mapping between DTOs and entities should be as straightforward as possible. To achieve this, DTOs should be mere data containers and stick closely to the underlying entites. Ideally, the mapping can be automated and becomes transparent.





What follows is a sample application of the DTO pattern. The key feature is the seamless conversion between domain model and DTOs. The Orika mapper proved brilliant for this job.





The application is a simple address book, Person and Address being the only entities:

@Entity public class Person { @Id private Long id; @Column(name = "first_name", nullable=false) private String firstName; @Column(name = "last_name", nullable=false) private String lastName; @Column(nullable=false, unique=true) private String email; @OneToMany(mappedBy = "person") private Collection<Address> addresses; ... } @Entity public class Address { @Id private Long id; // The usual address fields (street, city, etc.) @ManyToOne private Person person; ... }