这节主要介绍下@AfterMapping
1.添加新的业务类
data class Apple(var appleId:Int, var appleName:String,var real:Boolean){ constructor():this(0,"",false)}data class AppleDto(var appleId:Int, var appleName:String,var description:String){ constructor():this(0,"","")}
2.添加映射
@Mapperabstract class AppleConverter { //忽略target description字段映射 @Mapping(target = "description",ignore = true) abstract fun convertToDto(apple: Apple) : AppleDto //忽略target real字段映射 @Mapping(target = "real",ignore = true) abstract fun convertToModel(appleDto: AppleDto) : Apple //convertToDto执行完成后手动给appleDto的description字段赋值 @AfterMapping protected fun afterConvertToDto(apple: Apple, @MappingTarget appleDto: AppleDto) { val description = if(apple.real) "水果" else "数码" appleDto.description = description } //convertToModel执行完成后手动给apple的real字段赋值 @AfterMapping protected fun afterConvertToModel(appleDto: AppleDto, @MappingTarget apple: Apple) { val real = if(appleDto.description == "水果") true else false apple.real = real }}
3.调用一下吧
val appleConverter = Mappers.getMapper(AppleConverter::class.java) val apple = Apple(1,"my apple",true) println(apple) val appleDto = appleConverter.convertToDto(apple) println(appleDto) val appleModel = appleConverter.convertToModel(appleDto) println(appleModel)
输出
Apple(appleId=1, appleName=my apple, real=true)AppleDto(appleId=1, appleName=my apple, description=水果)Apple(appleId=1, appleName=my apple, real=true)