Junior — Middle
Could you explain the role of Mapper in data transformation for DTO classes?
sobes.tech AI
Answer from AI
In the context of data transformation for DTO (Data Transfer Object) classes, a Mapper is responsible for converting between application layers — usually between database entities and DTOs used for data transfer, for example, in APIs.
The role of the Mapper includes:
- Isolating business logic from data presentation details.
- Simplifying and standardizing the data transformation process.
- Ensuring security by excluding the transfer of unnecessary or sensitive fields.
An example of a simple Mapper in Java:
public class UserMapper {
public static UserDTO toDTO(UserEntity entity) {
UserDTO dto = new UserDTO();
dto.setId(entity.getId());
dto.setName(entity.getName());
// other fields
return dto;
}
public static UserEntity toEntity(UserDTO dto) {
UserEntity entity = new UserEntity();
entity.setId(dto.getId());
entity.setName(dto.getName());
// other fields
return entity;
}
}
Thus, the Mapper simplifies support and development of the code, separating data transformation from business logic.