// assume getters and setters
class User {
long id;
String firstName;
String lastName;
String email;
String password;
String securitySocialNumber;
boolean isAdmin;
}
And wanted to expose just the id, firstName, and email. By using ModelMapper we would have to create a DTO like this:
// assume getters and setters
class UserDTO {
long id;
String firstName;
String email;
}
And then call ModelMapper as follows:
ModelMapper modelMapper = new ModelMapper();
// user here is a prepopulated User instance
UserDTO userDTO = modelMapper.map(user, UserDTO.class);
That is, only by defining the structure that we want to expose and by calling modelMapper.map, we achieve our goal and hide what is not meant to be exposed. One might argue that libraries like Jackson provide annotations to ignore some properties when serializing objects, but this solution restrict developers to a single way to express their entities. By using DTOs and ModelMapper, we can provide as many different versions (with different structures) of our entities as we want.
A data transfer object (DTO) is an object that is used to encapsulate data, and send it from one subsystem of an application to another. DTOs are commonly used in n-tiered web applications to transfer data between model and view. A DTO differs to the model and DAOs (which persist and retrieve data from the database) in that a DTO does not have contain any business logic except for storage and retrieval of its own data. A DTO’s data can be aggregated from several database tables or other data sources. The main benefit of using DTOs is that they can reduce the amount of data that needs to be sent across the wire in web applications.
The following text describes a simple example of a DTO in a Java-based library-like web application. The model of the application consists of two simple classes, Person and Book. The main class is Person which has the following attributes:
private int personId;
private String name;
private String address;
private String telephone;
private String email;
private ArrayList
Comments
Post a Comment