对象转换: 对象的分层涉及到各个层级之间的对象转换(Entity2DTO , DTO2VO, VO2DTO,DTO2Entity等),传统的采用set/get 方法硬编码实现写的代码比较多;或者采用Bean的copy处理性能受影响
新的处理方式:采用工具在可以在编译器动态生成Java实现类,同时可以集成spring的生态体系,纯粹的是面向接口实现方式
实现方式:
-
项目中需要添加依赖配置
<org.mapstruct.version>1.3.0.Final</org.mapstruct.version><dependency><groupId>org.mapstruct</groupId><artifactId>mapstruct</artifactId><version>${org.mapstruct.version}</version></dependency><dependency><groupId>org.mapstruct</groupId><artifactId>mapstruct-processor</artifactId><version>${org.mapstruct.version}</version></dependency> -
定义接口类设置映射关系
importcom.sinaif.core.dto.UserDto;importcom.sinaif.core.entity.UserEntity;importorg.mapstruct.Mapper;importorg.mapstruct.Mapping;importorg.mapstruct.Mappings;importjava.util.List;/*** @Author allen_chen* @Description 用户POJO对象转换接口* @Date 2019/7/29 11:53* @Param* @return**/@Mapper(componentModel ="spring")publicinterfaceUserTransfer {/*** @Author allen_chen* @Description eentity转化为dto* @Date 2019/7/29 11:53* @Param [userEntity]* @return com.example.demo.common.base.dto.UserDto**/@Mappings({@Mapping(source ="phone",target ="cellphone"),@Mapping(source ="id",target ="userId")})publicUserDto entity2Dto(UserEntity userEntity);/*** @Author allen_chen* @Description dto转化为entity* @Date 2019/7/29 11:53* @Param [dto]* @return com.example.demo.common.base.entity.UserEntity**/@Mappings({@Mapping(source ="cellphone",target ="phone")})publicUserEntity dto2Entity(UserDto dto);@Mappings({@Mapping(source ="cellphone",target ="phone")})publicList<UserEntity> listDto2ListEntity(List<UserDto> dtoList);@Mappings({@Mapping(source ="phone",target ="cellphone")})publicList<UserDto> ListEntity2ListDto( List<UserEntity> entityList);} -
具体调用方式直接通过spring注入完成调用
@AutowiredUserTransfer userTransfer;@TestpublicvoidtestUserEntity2DtoTransfer(){UserEntity entity =newUserEntity();entity.setName("allen");entity.setNickName("allen.chen");entity.setCreTime(newDate());entity.setId(50L);entity.setPhone("135060309");UserDto dto = userTransfer.entity2Dto(entity);Assert.assertNotNull(dto);Assert.assertEquals("allen",dto.getName());}@TestpublicvoidtestUserDto2EntityTransfer(){UserDto dto =newUserDto();dto.setName("allen");dto.setNickName("allen.chen");UserEntity entity = userTransfer.dto2Entity(dto);Assert.assertNotNull(entity);Assert.assertEquals("allen",entity.getName());} - 注意事项:
1) 如果项目中有用到swagger的需要排除下依赖:
<exclusions> <exclusion> <artifactId>mapstruct</artifactId> <groupId>org.mapstruct</groupId> </exclusion></exclusions> |
2)更多使用eclipse IDEA 工具需要参考官网地址:http://mapstruct.org/documentation/ide-support/