1.引入依赖
// https://mvnrepository.com/artifact/com.baomidou/mybatisplus-spring-boot-starter
implementation 'com.baomidou:mybatisplus-spring-boot-starter:1.0.5'
// https://mvnrepository.com/artifact/com.github.jeffreyning/mybatisplus-plus
implementation 'com.github.jeffreyning:mybatisplus-plus:1.5.1-RELEASE'
// https://mvnrepository.com/artifact/org.mapstruct/mapstruct
implementation 'org.mapstruct:mapstruct:1.5.5.Final'
// https://mvnrepository.com/artifact/org.mapstruct/mapstruct-processor
implementation 'org.mapstruct:mapstruct-processor:1.5.5.Final'
// If you are using mapstruct in test code
testAnnotationProcessor "org.mapstruct:mapstruct-processor:1.5.5.Final"
// https://mvnrepository.com/artifact/org.projectlombok/lombok
compileOnly 'org.projectlombok:lombok:1.18.30'
MapStruct 代码生成器可以使用注释处理器选项进行配置。
当直接调用 javac 时,这些选项以 -Akey=value 的形式传递给编译器。通过 Maven 使用 MapStruct 时,可以在 Maven 处理器插件的配置中使用传递任何处理器选项,如下所示:compilerArgs
compileJava {
options.compilerArgs += [
'-Amapstruct.suppressGeneratorTimestamp=true',
'-Amapstruct.suppressGeneratorVersionInfoComment=true',
'-Amapstruct.verbose=true'
]
}
2. 定义一个映射器
2.1 基本映射
要创建映射器,只需使用所需的映射方法定义一个Java接口,并用注释对其进行org.mapstruct.Mapper注释:
该@Mapper注释将使得MapStruct代码生成器创建的执行PersonMapper 过程中生成时的界面。
在生成的方法实现中,源类型(例如Person)的所有可读属性都将被复制到目标类型(例如PersonDTO)的相应属性中:
-
当一个属性与其目标实体对应的名称相同时,它将被隐式映射。
-
当属性在目标实体中具有不同的名称时,可以通过@Mapping注释指定其名称。
如果不指定@Mapping,默认映射name相同的field
如果映射的对象field name不一样,通过 @Mapping 指定。
忽略字段加@Mapping#ignore() = true