do转dto 等映射插件mapstruct及嵌套解决


引入编译依赖

<properties>
    <project-war-name>com-test</project-war-name>
    <project.build.complier>1.8</project.build.complier>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven-compiler-plugin.version>3.6.1</maven-compiler-plugin.version>
    <maven-resources-plugin.version>3.0.2</maven-resources-plugin.version>
    <maven-source-plugin.version>3.0.1</maven-source-plugin.version>
    <maven-deploy-plugin.version>2.8.2</maven-deploy-plugin.version>
    <maven-war-plugin.version>2.2</maven-war-plugin.version>
    <mapstruct.version>1.4.2.Final</mapstruct.version>
    <lombok.version>1.16.20</lombok.version>
</properties>
<build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven-compiler-plugin.version}</version>
                <configuration>
                    <source>${project.build.complier}</source>
                    <target>${project.build.complier}</target>
                    <encoding>${project.build.sourceEncoding}</encoding>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.mapstruct</groupId>
                            <artifactId>mapstruct-processor</artifactId>
                            <version>${mapstruct.version}</version>
                        </path>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                            <version>${lombok.version}</version>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>${maven-resources-plugin.version}</version>
                <configuration>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>${maven-source-plugin.version}</version>
                <configuration>
                    <skipSource>true</skipSource>
                </configuration>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>${maven-deploy-plugin.version}</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>${maven-war-plugin.version}</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                    <warName>${project-war-name}</warName>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${maven-surefire-plugin.version}</version>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

java

@Mapper
public interface UserCopier {

    UserCopier INSTANCE = Mappers.getMapper(UserCopier.class);

    @Mappings({
    })
    DtoPlfUserQueryInfo plfUserToDtoPlfUserQueryInfo(DoPlfUser user);

    List<DtoPlfUserQueryInfo> plfUserToDtoPlfUserQueryInfo(List<DoPlfUser> addrList);

    @Mappings({
    })
    DoPlfUser plfUserToDtoUserInsert(PlfUserInsertRequest user);

    //bean copy
    @Mappings({
    })
    DoPlfUser plfUserToDtoUserStop(PlfUserStopRequest req);

    //bean copy
    @Mappings({
            @Mapping(source = "userName", target = "userName"),
            @Mapping(source = "userMobile", target = "userMobile"),
            @Mapping(source = "userPwd", target = "userPwd"),
            @Mapping(source = "userCode", target = "userCode")
    })
    DtoMyBaseInfo plfUserToDtoMyBaseInfo(DoPlfUser user);


    @Mappings({
            @Mapping(source = "plfOrgId", target = "plfOrgId"),
            @Mapping(source = "plfOrgName", target = "plfOrgName"),
            @Mapping(source = "noDept", target = "noDept"),
            @Mapping(source = "creatorName", target = "creatorName"),
            @Mapping(source = "createTime", target = "createTime"),
            @Mapping(source = "stopUserName", target = "stopUserName"),
            @Mapping(source = "stopTime", target = "stopTime"),
            @Mapping(source = "status", target = "status")
    })
    DtoOrgInfo plfOperOrgToDtoOrgInfo(DoPlfOperOrg doPlfOperOrg);

    List<DtoOrgInfo> plfOperOrgToDtoOrgInfo(List<DoPlfOperOrg> doPlfOperOrgList);

}

新版无需配置到插件中
直接引入jar即可

        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct</artifactId>
            <version>1.4.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct-processor</artifactId>
            <version>1.4.1.Final</version>
        </dependency>

实现类

/**
 * description: 映射基础类
 *
 * @author: 倔强的老铁
 * @date: 2021/12/24 10:31
 * @version: 1.0
 */
@MapperConfig
public interface BaseMapping<SOURCE, TARGET> {

    /**
     * 映射同名属性
     */
    //@Mapping(target = "createTime", dateFormat = "yyyy-MM-dd HH:mm:ss")
    TARGET sourceToTarget(SOURCE var1);

    /**
     * 反向,映射同名属性
     */
    @InheritInverseConfiguration(name = "sourceToTarget")
    SOURCE targetToSource(TARGET var1);

    /**
     * 映射同名属性,集合形式
     */
    @InheritConfiguration(name = "sourceToTarget")
    List<TARGET> sourceToTarget(List<SOURCE> var1);

    /**
     * 反向,映射同名属性,集合形式
     */
    @InheritConfiguration(name = "targetToSource")
    List<SOURCE> targetToSource(List<TARGET> var1);

    /**
     * 映射同名属性,集合流形式
     */
    List<TARGET> sourceToTarget(Stream<SOURCE> stream);

    /**
     * 反向,映射同名属性,集合流形式
     */
    List<SOURCE> targetToSource(Stream<TARGET> stream);
}

实体Copier

@Mapper
public interface PopBillImportCopier extends BaseMapping<DoPopBillImport, DtoPopBillImport>{
    PopBillImportCopier INSTANCE = Mappers.getMapper(PopBillImportCopier.class);
}

用户类转换例子
示例使用的是 Spring 的方式,@Mapper 注解的 componentModel 属性值为 spring,不过应该大多数都用的此模式进行开发。
@Mapping用于配置对象的映射关系,示例中 User 对象性别属性名为 sex,而UserVo对象性别属性名为gender,因此需要配置 target 与 source 属性。
password 字段不应该返回到前台,可以采取两种方式不进行转换,第一种就是在vo对象中不出现password字段,第二种就是在@Mapping中设置该字段 ignore = true。
MapStruct 提供了时间格式化的属性 dataFormat,支持Date、LocalDate、LocalDateTime等时间类型与String的转换。示例中birthday 属性为 LocalDate 类型,可以无需指定dataFormat自动完成转换,而LocalDateTime类型默认使用的是ISO格式时间,在国内往往不符合需求,因此需要手动指定一下 dataFormat。

实现 User 与 UserVo 对象的转换器

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

@Mapper(componentModel = "spring")
public interface UserMapping extends BaseMapping<User, UserVo> {

    @Mapping(target = "gender", source = "sex")
    @Mapping(target = "createTime", dateFormat = "yyyy-MM-dd HH:mm:ss")
    @Override
    UserVo sourceToTarget(User var1);

    @Mapping(target = "sex", source = "gender")
    @Mapping(target = "password", ignore = true)
    @Mapping(target = "createTime", dateFormat = "yyyy-MM-dd HH:mm:ss")
    @Override
    User targetToSource(UserVo var1);

    default List<UserConfig> strConfigToListUserConfig(String config) {
        return JSON.parseArray(config, UserConfig.class);
    }

    default String listUserConfigToStrConfig(List<UserConfig> list) {
        return JSON.toJSONString(list);
    }
}

如果项目中也同时使用到了 Lombok,一定要注意 Lombok的版本要等于或者高于1.18.10,否则会有编译不通过的情况发生,笔者掉进这个坑很久才爬了出来,希望各位不要重复踩坑。

嵌套,mapstruct 会发现,只要 变量名相同
对象或者数组都可以自动映射,如下图

posted @ 2021-11-22 13:39  倔强的老铁  阅读(1205)  评论(0编辑  收藏  举报