這節主要介紹下如何調用其餘的mapperjava
1.修改上節用到的FlightConverter,新增List的映射app
@Mapper interface FlightConverter { fun convertToDto(flight: Flight) : FlightDto fun convertToModel(flightDto: FlightDto) : Flight fun flightToDtos(cars: List<Flight>): List<FlightDto> fun dtoToFlights(cars: List<FlightDto>): List<Flight> }
2.添加新的業務類this
import java.time.LocalDate data class Person(var firstName: String?, var lastName: String?, var phoneNumber: String?, var birthdate: LocalDate?, var flight: Flight?, var flights: List<Flight>) { // Necessary for MapStruct constructor() : this(null, null, null, null, null, listOf()) } import java.time.LocalDate data class PersonDto(var firstName: String?, var lastName: String?, var phone: String?, var birthdate: LocalDate?, var flightDto: FlightDto?, var flights:List<FlightDto>) { // Necessary for MapStruct constructor() : this(null, null, null, null,null, listOf()) }
3.添加業務類的映射code
//類中的方法,進行字段映射時會使用FlightConverter中定義的方法 @Mapper(uses = [FlightConverter::class]) interface PersonConverter { //配置對應字段 @Mappings(value = [ Mapping(source = "phoneNumber", target = "phone"), Mapping(source = "flight",target = "flightDto") ]) fun convertToDto(person: Person) : PersonDto //對convertToDto實現逆映射,若是若是有多個方法,能夠經過name屬性 //指定,如@InheritInverseConfiguration(name = "convertToDto") @InheritInverseConfiguration fun convertToModel(personDto: PersonDto) : Person }
4.調用一下吧get
val converter = Mappers.getMapper(PersonConverter::class.java) // or PersonConverterImpl() val flight = Flight(flightId = 1,flightName = "CX 101") val person = Person("Samuel", "Jackson", "0123 334466", LocalDate.of(1948, 12, 21), flight, listOf(flight)) println(person) val personDto = converter.convertToDto(person) println(personDto) val personModel = converter.convertToModel(personDto) println(personModel)
輸出it
Person(firstName=Samuel, lastName=Jackson, phoneNumber=0123 334466, birthdate=1948-12-21, flight=Flight(flightId=1, flightName=CX 101), flights=[Flight(flightId=1, flightName=CX 101)]) PersonDto(firstName=Samuel, lastName=Jackson, phone=0123 334466, birthdate=1948-12-21, flightDto=FlightDto(flightId=1, flightName=CX 101), flights=[FlightDto(flightId=1, flightName=CX 101)]) Person(firstName=Samuel, lastName=Jackson, phoneNumber=0123 334466, birthdate=1948-12-21, flight=Flight(flightId=1, flightName=CX 101), flights=[Flight(flightId=1, flightName=CX 101)])
發現已經生效了io