多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
**1. 两个字段名不一致的实体类** ```java @Data public class Car { private Integer carId; private String carName; } @Data public class CarDto { private Integer carDtoId; private String carDtoName; } ``` **2. 映射接口** ```java @Mapper public interface CarMapper { CarMapper INSTANCE = Mappers.getMapper(CarMapper.class); /** * 使用@Mapping的source和target让两个实体类的属性进行对应 */ @Mapping(source = "carId", target = "carDtoId") @Mapping(source = "carName", target = "carDtoName") CarDto toDto(Car source); } ``` **3. 测试** ```java @Test public void testCarMapper() { Car car = new Car(); car.setCarId(1001); car.setCarName("红旗"); CarDto carDto = CarMapper.INSTANCE.toDto(car); //Car:Car(carId=1001, carName=红旗) System.out.println("Car:" + car); //Car-->CarDto:CarDto(carDtoId=1001, carDtoName=红旗) System.out.println("Car-->CarDto:" + carDto); } ``` **4. 查看映射接口被Mapstruct编译后的代码** ```java public class CarMapperImpl implements CarMapper { public CarMapperImpl() { } public CarDto toDto(Car source) { if (source == null) { return null; } else { CarDto carDto = new CarDto(); carDto.setCarDtoId(source.getCarId()); carDto.setCarDtoName(source.getCarName()); return carDto; } } } ```