注解@Mapper(componentModel = "spri
2019-08-13 本文已影响0人
炒面Z
注解@Mapper(componentModel = "spring")-自动生成VO-DO的模型映射
场景: 插件可以自动生成实现类,实现DTO-DO各种模型之间的字段映射(不仅仅限制于DTO-DO)
- 第一步: 引入pom文件
<!--mapStruct依赖-->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>1.2.0.CR1</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.2.0.CR1</version>
<scope>provided</scope>
</dependency>
- 第二步:
@Mapper(componentModel = "spring")
public interface RoleConvert {
RoleDO convert(RoleCreateDTO roleCreateDTO);
}
使用:
@Autowired
private RoleConvert roleConvert;
// 转化
RoleDO roleDO = roleConvert.convert(roleCreateDTO);
- 第三步: 看编译后自动生成的实现类
编译后自动生成了RoleConvert 的实现类 RoleConvertImpl.class
image.png- 第四步: 高级用法,指定映射字段
@Mapper(componentModel = "spring")
public interface ProductConverter {
@Mappings({
@Mapping(source = "id",target = "productId"),
@Mapping(source = "title",target = "productName"),
@Mapping(source = "price",target = "salePrice"),
@Mapping(source = "sellPoint",target = "subTitle"),
@Mapping(source = "image",target = "picUrl")
})
ProductDto item2Dto(ItemDocument item);
}