🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
**1. 两个存在字段类型不一致的实体类** ```java @Data public class Flight { private String flightId; private String flightName; private String createTime; } @Data public class FlightDto { private String flightDtoId; private String flightDtoName; private LocalDateTime createTime; } ``` **2. 映射接口** ```java //imports将表达式用到的相关类导入到当前类中 @Mapper(imports = {DateUtils.class, UUID.class}) public interface FlightMapper { FlightMapper INSTANCE = Mappers.getMapper(FlightMapper.class); //flightDtoId取值为表达式expression的返回值 @Mapping(target = "flightDtoId", expression = "java(UUID.randomUUID().toString())") //当flightName为null时,flightDtoName取值为defaultExpression的返回值 @Mapping(source = "flightName", target = "flightDtoName", defaultExpression = "java(UUID.randomUUID().toString())") //当类型不一致时可以使用expression表达式进行转换 @Mapping(target = "createTime", expression = "java(DateUtils.strToLocalDateTime(source.getCreateTime()))") FlightDto toDto(Flight source); //如果不使用imports属性,则需要在表达式中写全名 //@Mapping(, expression="java(java.util.UUID.randomUUID().toString())") } ``` 我定义的`DateUtils.strToLocalDateTime(...)`方法如下: ```java public class DateUtils { public static LocalDateTime strToLocalDateTime(String str) { DateTimeFormatter df = DateTimeFormatter.ofPattern("yyy-MM-dd HH:mm:ss"); return LocalDateTime.parse(str, df); } } ``` **3. 测试** ```java @Test public void testFlightMapper() { Flight flight = new Flight(); flight.setFlightId("10001"); flight.setFlightName(null ); flight.setCreateTime("2021-10-21 10:38:29"); FlightDto flightDto = FlightMapper.INSTANCE.toDto(flight); //Flight:Flight(flightId=10001, flightName=null, createTime=2021-10-21 10:38:29) System.out.println("Flight:" + flight); //FlightDto:FlightDto(flightDtoId=48c367e7-..., flightDtoName=2bc3454e-..., createTime=2021-10-21T10:38:29) System.out.println("FlightDto:" + flightDto); } ``` **4. 查看映射接口被Mapstruct编译后的代码** ```java public class FlightMapperImpl implements FlightMapper { public FlightMapperImpl() { } public FlightDto toDto(Flight source) { if (source == null) { return null; } else { FlightDto flightDto = new FlightDto(); if (source.getFlightName() != null) { flightDto.setFlightDtoName(source.getFlightName()); } else { flightDto.setFlightDtoName(UUID.randomUUID().toString()); } flightDto.setFlightDtoId(UUID.randomUUID().toString()); flightDto.setCreateTime(DateUtils.strToLocalDateTime(source.getCreateTime())); return flightDto; } } } ```