MapStruct 简介
两个对象之间的数据映射。
设有两个相似的汽车类Cat.java 及 CarDto.java
public class Car {
private String make;
private int numberOfSeats;
private CarType type;
//constructor, getters, setters etc.
}
一、映射接口
为了转换需要定义一个接口
-
CarMapper.java
-
@Mapper
public interface CarMapper
{
CarMapper INSTANCE = Mappers.getMapper( CarMapper.class );
@Mapping(source = "numberOfSeats", target = "seatCount")
/*target*/CarDto carToCarDto(/*source*/Car car);
}
@Mapper
注解使MapStruct在编译时进行映射与转换.
carToCarDto
输入源对象返回返回目标对象,名称无所谓.
使用@Mapping` 注解来配置字段对应.
自动类型转换.
可以有多个转换方法,MapStruct为每个方法分别生成一个实例.
映射类中可以包含一个映射类的实例.
二、使用映射类
-
CarMapperTest.java
-
@Test
public void shouldMapCarToDto()
{
//given
Car car = new Car( "Morris", 5, CarType.SEDAN );
//when
CarDto carDto = CarMapper.INSTANCE.carToCarDto( car );
//then
assertThat( carDto ).isNotNull();
assertThat( carDto.getMake() ).isEqualTo( "Morris" );
assertThat( carDto.getSeatCount() ).isEqualTo( 5 );
assertThat( carDto.getType() ).isEqualTo( "SEDAN" );
}
三、注入spring ioc
@Mapper(componentModel = "spring")
public interface CarMapping {
/**
* 用来调用实例 实际开发中可使用注入Spring 不写
*/
// CarMapping CAR_MAPPING = Mappers.getMapper(CarMapping.class);
/**
* 源类型 目标类型 成员变量相同类型 相同变量名 不用写{@link Mapping}来映射
*
* @param car the car
* @return the car dto
*/
@Mapping(target = "type", source = "carType.type")
@Mapping(target = "seatCount", source = "numberOfSeats")
CarDTO carToCarDTO(Car car);
}
四、插件
MapStruct Support