這節主要介紹下@AfterMappingjava
1.添加新的業務類app
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.添加映射this
@Mapper abstract 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.調用一下吧code
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)
輸出ip
Apple(appleId=1, appleName=my apple, real=true) AppleDto(appleId=1, appleName=my apple, description=水果) Apple(appleId=1, appleName=my apple, real=true)