High-performance entity class conversion tool MapStruct tutorial

1. What is MapStruct

​ We will encounter a lot of bean copying processes during the development process. The simplest and rude method is the set/get method. Of course, this is also the most stupid method. The code is too long and cumbersome. Secondly, when the framework BeanUtils uses reflection will affect performance. Although we can cache reflection information to improve performance. But like this, the type and name must be the same to be mapped. In many cases, because the nouns used by different teams are different, a lot of manual set/get functions are still required.

MapStruct solves these problems. It is an annotation processor that generates type-safe, high-performance, and dependency-free JavaBean mapping code.

  • annotation processor
  • Can generate the mapping code between JavaBean
  • Type safety, high performance, no dependencies

2. Advantage analysis

high performance

This is relative to reflection. Reflection needs to read the content of the bytecode, which will cost a lot. The code generated by MapStruct is similar to human handwriting. Speed ​​can be guaranteed.

Simple to use

If it is fully mapped, it is certainly not as simple to use as reflection. Use tools like BeanUtils to get it done with one statement. However, if special matching (special type conversion, many-to-one conversion, etc.) is required, it is relatively simple.

Basically, when using it, we only need to declare an interface, write the corresponding method under the interface, and then it can be used. Of course, if there are special circumstances, additional processing is required.

code independent

The generated code is self-contained and has no runtime dependencies.

easy to debug

In our generated code, we can easily debug.

3. How to use

pom import

    <!--  mapStruct开始  -->
    <dependency>
        <groupId>org.mapstruct</groupId>
        <artifactId>mapstruct</artifactId>
        <version>1.4.2.Final</version>
    </dependency>
    <dependency>
        <groupId>org.mapstruct</groupId>
        <artifactId>mapstruct-jdk8</artifactId>
        <version>1.4.2.Final</version>
    </dependency>
    <dependency>
        <groupId>org.mapstruct</groupId>
        <artifactId>mapstruct-processor</artifactId>
        <version>1.4.2.Final</version>
    </dependency>
    <!--  mapStruct结束  -->

Entity class

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student implements Serializable {
    /**
     * id
     */
    private Integer id;
    /**
     * 学生姓名
     */
    private String name;
    /**
     * 年龄
     */
    private Integer age;
    /**
     * 性别
     */
    private String sex;
}

Prepare for VO class

@Data
@NoArgsConstructor
@AllArgsConstructor
public class StudentRequestVo {

    /**
     * id
     */
    private Integer studentId;
    /**
     * 学生姓名
     */
    private String studentName;
    /**
     * 年龄
     */
    private Integer studentAge;

}

define converter

	//这个注解是MapStruct得注解,不是mybatis注解
	@Mapper(componentModel = "spring", injectionStrategy = InjectionStrategy.CONSTRUCTOR)
public interface StudentMapStrut {

    @Mappings({
            @Mapping(target = "id",source = "studentId"),
            @Mapping(target = "name",source = "studentName"),
            @Mapping(target = "age",source = "studentAge")
    })
    Student studentConvert(StudentRequestVo studentRequestVo);

}

use

 Student student = studentMapStrut.studentConvert(new StudentRequestVo(1, "张三", 15));
List exchange
@Mapper(componentModel = "spring", injectionStrategy = InjectionStrategy.CONSTRUCTOR)
public interface StudentMapStrut {

    @Mappings({
            @Mapping(target = "id",source = "studentId"),
            @Mapping(target = "name",source = "studentName"),
            @Mapping(target = "age",source = "studentAge")
    })
    Student studentConvert(StudentRequestVo studentRequestVo);

    List<Student> studentListConvert(List<StudentRequestVo> studentRequestVos);

}
Multiple objects map to one object
//老师学生vo
@Data
@NoArgsConstructor
@AllArgsConstructor
public class StudentAndTeacher implements Serializable {
    /**
     * id
     */
    private Integer id;
    /**
     * 学生姓名
     */
    private String studentName;
    /**
     * 老师姓名
     */
    private String teacherName;
}

//学生vo
@Data
@NoArgsConstructor
@AllArgsConstructor
public class StudentRequestVo {

    /**
     * id
     */
    private Integer studentId;
    /**
     * 学生姓名
     */
    private String studentName;
    /**
     * 年龄
     */
    private Integer studentAge;
}
//老师vo
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TeacherRequestVo {

    /**
     * id
     */
    private Integer teacherId;
    /**
     * 学生姓名
     */
    private String teacherName;
    /**
     * 年龄
     */
    private Integer teacherAge;

}

mapped to an object

    @Mappings({
        @Mapping(target = "studentName",source = "studentRequestVo.studentName"),
        @Mapping(target = "teacherName",source = "teacherRequestVo.teacherName")
})
StudentAndTeacher studentAndTeacherConvert(StudentRequestVo studentRequestVo,TeacherRequestVo teacherRequestVo);

custom conversion

Taking object conversion as an example, we want to uniformly store those under 20 years old as 0, and uniformly store those over 20 years old as 1.

    @Mappings({
        @Mapping(target = "id",source = "studentId"),
        @Mapping(target = "name",source = "studentName"),
        @Mapping(target = "age",expression = "java(com.example.demo.mapstrut.MapStructUtil.ageConvert(studentRequestVo.getStudentAge()))")
})
Student studentConvert(StudentRequestVo studentRequestVo);

	public class MapStructUtil {

    public static Integer ageConvert(Integer studentAge){
        if (studentAge<=20){
            return 0;
        }else {
            return 1;
        }
    }
}

4. Summary:
mapstruct also has many functions, such as dateFormat and numberFormat to realize custom conversion, and you can refer to this article for daily use. For more details, please refer to the official website: https://mapstruct.org/documentation/stable/reference/html/

​Follow
my WeChat public
accountinsert image description here

Guess you like

Origin blog.csdn.net/CharlesYooSky/article/details/126004466