美文网首页
注解@Mapper(componentModel = "spri

注解@Mapper(componentModel = "spri

作者: 炒面Z | 来源:发表于2019-08-13 12:48 被阅读0次

注解@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);
}

相关文章

网友评论

      本文标题:注解@Mapper(componentModel = "spri

      本文链接:https://www.haomeiwen.com/subject/rtyvjctx.html