1.引入kapt插件及mapstruct相关包
//kotlin 1.2.60使用mapstruct有bug
kotlinVersion = '1.2.61'
//使用kapt插件
apply plugin: 'kotlin-kapt'
//引用mapstruct包
compile "org.mapstruct:mapstruct-jdk8:${mapstructVersion}"
//启用注解编译
kapt "org.mapstruct:mapstruct-processor:${mapstructVersion}"
//测试时使用
kaptTest "org.mapstruct:mapstruct-processor:${mapstructVersion}"
2.创建数据模型,用来演示mapping
//mapstruct要求有一个默认构造
data class Flight(var flightId:Int,
var flightName:String){
constructor():this(0,"")
}
data class FlightDto(var flightId:Int,
var flightName:String){
constructor():this(0,"")
}
3.创建映射关系
@Mapper
interface FlightConverter {
fun convertToDto(flight: Flight) : FlightDto
fun convertToModel(flightDto: FlightDto) : Flight
}
4.运行一下吧
val flightConverter = Mappers.getMapper(FlightConverter::class.java)
val flight = Flight(flightId = 1, flightName = "CX 101")
val flightDto = flightConverter.convertToDto(flight)
val flightModel = flightConverter.convertToModel(flightDto)
println("flight=${flight}")
println("flightDto=${flightDto}")
println("flightModel=${flightModel}")
输出
flight=Flight(flightId=1, flightName=CX 101)
flightDto=FlightDto(flightId=1, flightName=CX 101)
flightModel=Flight(flightId=1, flightName=CX 101)
5.解惑 为什么能直接映射成功呢,我们只定义了一个接口,让我们它自动生成的实现类看一下
import javax.annotation.Generated;
@Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2018-08-28T19:12:56+0800",
comments = "version: 1.3.0.Beta1, compiler: javac, environment: Java 1.8.0_172 (Oracle Corporation)"
)
public class FlightConverterImpl implements FlightConverter {
@Override
public FlightDto convertToDto(Flight flight) {
if ( flight == null ) {
return null;
}
FlightDto flightDto = new FlightDto();
flightDto.setFlightId( flight.getFlightId() );
flightDto.setFlightName( flight.getFlightName() );
return flightDto;
}
@Override
public Flight convertToModel(FlightDto flightDto) {
if ( flightDto == null ) {
return null;
}
Flight flight = new Flight();
flight.setFlightId( flightDto.getFlightId() );
flight.setFlightName( flightDto.getFlightName() );
return flight;
}
}
yes,这就是它能mapping的秘密