这节主要介绍下如何调用其余的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