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

原文链接:Convert entity to DTO in Springboot

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容