- 我的技术博客:https://nezha.github.io,https://nezhaxiaozi.coding.me
- 我的简书地址:https://www.jianshu.com/u/a5153fbb0434
本文的代码地址:GitHub MapStruct Demo
有 Enum 类型
MapStruct
可以非常轻松的将 Bean 对象映射到 DTO 对象中用于传输。
MapStruct
会在编译阶段实现其接口。
要是
Bean
中有Enum
类型,需要去对应DTO
中的String
,需要注意以下几点:
Bean
中重写setType(String type)
方法
DTO
中重写setType(CarType carType)
方法
1.Bean
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Car {
private String make;
private int numberOfSeats;
private CarType type;
public void setType(String type) {
this.type = CarType.convert(type);
}
}
2.Dto
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CarDto {
private String make;
private int seatCount;
private String type;
private String description;
public void setType(CarType carType) {
this.type = carType.getType();
}
}
3.mapstruct接口
@Mapper(
componentModel = "spring",
nullValueCheckStrategy = ALWAYS,
nullValueMappingStrategy = RETURN_DEFAULT)
public interface CarMapper {
CarMapper INSTANCE = Mappers.getMapper(CarMapper.class);
@Mappings({
@Mapping(source = "numberOfSeats", target = "seatCount"),
@Mapping(target = "description", ignore = true)
})
CarDto carToCarDto(Car car);
Car carDtoToCar(CarDto carDto);
}
4.TEST
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class MapstructApplicationTests {
@Autowired
private CarMapper carMapper;
@Test
public void mapCarToDto() {
//given
Car car = new Car("Morris", 5, CarType.SAIC);
//when
CarDto carDto = carMapper.carToCarDto(car);
//then
Assert.assertNotNull(carDto);
Assert.assertEquals("Morris", carDto.getMake());
Assert.assertEquals("上汽", carDto.getType());
log.info("输出的CarDto是:{}", JSON.toJSONString(carDto));
}
@Test
public void carDtoToBean(){
CarDto carDto = new CarDto("Morris",10,"奥迪","真的很不错");
Car car = carMapper.carDtoToCar(carDto);
log.info("输出的Car是:{}",JSON.toJSONString(car));
}
}
枚举类:
@Getter
public enum CarType {
BMW(1, "宝马"),
AUDI(2, "奥迪"),
SAIC(3, "上汽");
private Integer code;
private String type;
CarType(Integer code, String type) {
this.code = code;
this.type = type;
}
public static CarType convert(String type) {
switch (type) {
case "宝马":
return BMW;
case "奥迪":
return AUDI;
case "上汽":
return SAIC;
}
return null;
}
}