来源:微信公众号 - DD程序鹅
原文:https://mp.weixin.qq.com/s/PwML9O0PUY82bETHv2Q3fA
版权声明:本文为博主原创文章,转载请附上原文链接!
更多系列可以搜索上面公众号,提前查阅。
在开发过程中,实体和DTO直接进行映射或者转换时,通常想到的方式:
①使用setters /getters方法直接赋值
②若是属性相同还可以使用工具类BeanUtils(Spring)
那属性不同的时候,只能使用set/get方法直接赋值了。
当属性不多时还好,那么当属性比较多时怎么办呢,有没有更好的办法呢,答案是有的!!!
是什么
MapStruct是一个代码生成器,它基于约定优于配置的方法极大地简化了Java bean类型之间映射的实现。
生成的映射代码使用简单的方法调用,因此快速,类型安全且易于理解。
与其他映射框架相比,MapStruct在编译时生成Bean映射,以确保高性能。
引入Maven
<org.mapstruct.version>1.4.2.Final</org.mapstruct.version>
<lombok.version>1.18.4</lombok.version>
<maven-compiler-version>3.8.1</maven-compiler-version>
...
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>${org.mapstruct.version}</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${org.mapstruct.version}</version>
</dependency>
示例
@Data
@AllArgsConstructor
public class Car {
private String make;
private int numberOfSeats;
private CarType type;
}
@Data
public class CarDto {
private String make;
private int seatCount;
private String type;
private String color;
private Double price;
}
@Data
@AllArgsConstructor
public class CarAttrDto {
private String vcolor;
private Double dprice;
}
public enum CarType {
SEDAN
}
@Mapper
public interface CarMapper {
CarMapper INSTANCE = Mappers.getMapper( CarMapper.class );
@Mapping(source = "car.numberOfSeats", target = "seatCount")
CarDto carToCarDto(Car car);
@Mappings({
@Mapping(source = "car.make", target = "make"),
@Mapping(source = "car.numberOfSeats", target = "seatCount"),
@Mapping(source = "carAttrDto.vcolor", target = "color"),
@Mapping(source = "carAttrDto.dprice", target = "price")
})
CarDto carToCarDto2(Car car, CarAttrDto carAttrDto);
}
public class CarMapperTest {
@Test
public void shouldMapCarToDto() {
Car car = new Car( "Morris", 5, CarType.SEDAN );
CarDto carDto = CarMapper.INSTANCE.carToCarDto(car);
Assert.assertNotNull(carDto);
Assert.assertEquals(carDto.getMake(), car.getMake());
Assert.assertEquals(carDto.getSeatCount(), car.getNumberOfSeats());
Assert.assertEquals(carDto.getType(), car.getType().name());
}
@Test
public void shouldMapCarToDto2() {
Car car = new Car( "Morris", 5, CarType.SEDAN );
CarAttrDto carAttrDto = new CarAttrDto("白色", 200000.0);
CarDto carDto = CarMapper.INSTANCE.carToCarDto2(car,carAttrDto);
Assert.assertNotNull(carDto);
Assert.assertEquals(carDto.getMake(), car.getMake());
Assert.assertEquals(carDto.getSeatCount(), car.getNumberOfSeats());
Assert.assertEquals(carDto.getType(), car.getType().name());
Assert.assertEquals(carDto.getColor(), carAttrDto.getVcolor());
Assert.assertEquals(carDto.getPrice(), carAttrDto.getDprice());
}
}
注意事项:
①lombok和maven-compiler-plugin版本
②@Mapping中属性相同时,source和target可不写
往期精彩回顾
ETL工具Kettle - Linux中安装与使用(集群-加快执行速度)