I used to map an entity to DTO in the service class by writing my own mapping method but recently I got to know about Model Mapper, all we need to do is just add model mapper dependency in pom.xml file.
Without using Model Mapper the code will look something like this:-
//pom.xml
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.4.2</version>
</dependency>
//UserService class
private UserDTO convertToDto(UserEntity userEntity) {
UserDTO userDTO = new UserDTO();
userDTO.setId(userEntity.getId());
userDTO.setEmailID(userEntity.getEmailID());
userDTO.setAbout(userEntity.getAbout());
userDTO.setName(userEntity.getName());
return userDTO;
}
or
//UserService class
public UserDTO mapUserEntityToUserDTO(UserEntity userEntity) {
return new UserDTO(userEntity.getId(),userEntity.getName(), userEntity.getEmailID(), userEntity.getAbout());
}
With Model mapper
//Service class
@Autowired private ModelMapper modelMapper;
private UserDTO convertToDto(UserEntity userEntity) {
UserDTO userDTO = modelMapper.map(userEntity, UserDTO.class);
return userDTO;
}
Top comments (4)
Hey Aastha! Great post!
Did you check out Mapstruct? I used it in my last project!
How do ModelMapper deal with nested fields or with different names of the same property?
Hey Michael!
Could you give me some examples of different names of the same property, some code or some link for reference.
Hi Michael!
I've heard about Mapstruct but never used it and never dealt with nested fields as well so have I no idea, will definitely edit the post, once I get to know about these things.
spring provides BeanUtils.copyProperties which uses introspect mechanisam, hence much faster. please try that too.!