kotlin使用mapstruct(一)

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的秘密

转载于:https://my.oschina.net/weidedong/blog/1935442

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值