DEV Community

Cover image for Convert entity to DTO in Springboot
Aastha Pandey
Aastha Pandey

Posted on

Convert entity to DTO in Springboot

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>

Enter fullscreen mode Exit fullscreen mode
//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;
    }
Enter fullscreen mode Exit fullscreen mode

or

//UserService class
public UserDTO mapUserEntityToUserDTO(UserEntity userEntity) {

        return new UserDTO(userEntity.getId(),userEntity.getName(), userEntity.getEmailID(), userEntity.getAbout());
    }
Enter fullscreen mode Exit fullscreen mode

With Model mapper

//Service class
@Autowired private ModelMapper modelMapper;
private UserDTO convertToDto(UserEntity userEntity) {
        UserDTO userDTO = modelMapper.map(userEntity, UserDTO.class);
      return userDTO;
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
miso profile image
Michael

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?

Collapse
 
aasthapandey profile image
Aastha Pandey

Hey Michael!
Could you give me some examples of different names of the same property, some code or some link for reference.

Collapse
 
aasthapandey profile image
Aastha Pandey

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.

Collapse
 
sankarsingh3 profile image
sankar singh

spring provides BeanUtils.copyProperties which uses introspect mechanisam, hence much faster. please try that too.!