推荐一个好用的实体映射工具:MapStruct

使用方法其实很简单的:

StudentDto

StudentPo

定义两个实体对象,现在如果需要将StudentDto转换为StudentPo对象的话,由于他们各自的属性都不一样,使用传统的转换工具就会显得比较麻烦,那么现在我们使用MapStruct的话就很简单了。

使用方法

添加依赖

<properties>
    <org.mapstruct.version>1.4.2.Final</org.mapstruct.version>
</properties>

<dependency>
     <groupId>org.mapstruct</groupId>
     <artifactId>mapstruct</artifactId>
     <version>${org.mapstruct.version}</version>
</dependency>

<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                    <encoding>UTF-8</encoding>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.mapstruct</groupId>
                            <artifactId>mapstruct-processor</artifactId>
                            <version>${org.mapstruct.version}</version>
                        </path>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                            <version>1.18.12</version>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>

定义转换接口

@Mapper
public interface ObjectConverter {
    ObjectConverter INSTANCE = Mappers.getMapper(ObjectConverter.class);

    /**
     * 将dto对象转为po对象
     * 如果两个对象的字段名是一样的,其实可以不用定义@Mapping
     * @param dto 源对象
     * @return 转换后的对象
     */
    @Mappings({@Mapping(source = "id", target = "stuId"),
            @Mapping(source = "name", target = "stuName"),
            @Mapping(source = "address", target = "stuAddress"),
            @Mapping(source = "age", target = "stuAge")})
    StudentPo dtoToPo(StudentDto dto);
}

使用

@SpringBootTest
public class MapStructTest {

    @Test
    public void mapStructTest() {
        StudentDto studentDto = new StudentDto(10, "刘备", "蜀国", 45);

        // 使用
        StudentPo studentPo = ObjectConverter.INSTANCE.dtoToPo(studentDto);
        System.out.println(studentPo);
    }
}

结果

image.png

注意:如果运行出现No property named “XXX“ exists in source parameter(s). Did you mean “null“?异常的话,有可能是lombok的版本太高了,可以试着将版本降低一点。

MapStruct不仅可以映射单个对象,还可以进行集合映射

@Mappings({@Mapping(source = "id", target = "stuId"),
            @Mapping(source = "name", target = "stuName"),
            @Mapping(source = "address", target = "stuAddress"),
            @Mapping(source = "age", target = "stuAge")})
    List<StudentPo> stosToPos(List<StudentDto> dtos);
List<StudentDto> dtos = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            StudentDto studentDto = new StudentDto(i, "刘备" + 1, "蜀国", 45);
            dtos.add(studentDto);
        }
        List<StudentPo> studentPos = instance.stosToPos(dtos);
        studentPos.forEach(System.out::println);

结果

image.png

还有一些特殊用法
image.png

比如我现在要将dto中的sex字段映射到po的时候,将1映射为男,2为女

// 接口添加方法
@Named("sexConverter")
    default String sexConverter(Integer sex) {
        if (sex == 1) {
            return "男";
        }
        return "女";
    }
@Mappings({@Mapping(source = "id", target = "stuId"),
            @Mapping(source = "name", target = "stuName"),
            @Mapping(source = "address", target = "stuAddress"),
            @Mapping(source = "age", target = "stuAge"),
            @Mapping(source = "sex", target = "stuSex", qualifiedByName = "sexConverter")}) // 加上这个属性即可,它会自动调用刚刚那个方法。
    StudentPo dtoToPo(StudentDto dto);

运行结果

StudentDto studentDto = new StudentDto(10, "刘备", "蜀国", 45,1);
        ObjectConverter instance = ObjectConverter.INSTANCE;

        // 使用
        StudentPo studentPo = instance.dtoToPo(studentDto);
        System.out.println(studentPo);

image.png

查看它给我们生成的实现类可以看到,它还是调用了set,get方法,完成后又调用目标对象的全参构造方法生成了一个对象进行返回。原理上其实不难理解。
image.png

好了,这就是MapStruct的基本使用方式了,工具其实还挺好用的,大家快去happy的用起来吧!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容