- 我的技術(shù)博客:https://nezha.github.io,https://nezhaxiaozi.coding.me
- 我的簡(jiǎn)書(shū)地址:http://www.reibang.com/u/a5153fbb0434
本文的代碼地址:GitHub MapStruct Demo
有 Enum 類型
MapStruct
可以非常輕松的將 Bean 對(duì)象映射到 DTO 對(duì)象中用于傳輸磕蛇。
MapStruct
會(huì)在編譯階段實(shí)現(xiàn)其接口瓶逃。
要是
Bean
中有Enum
類型谐丢,需要去對(duì)應(yīng)DTO
中的String
拳球,需要注意以下幾點(diǎn):
Bean
中重寫(xiě)setType(String type)
方法
DTO
中重寫(xiě)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,"奧迪","真的很不錯(cuò)");
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;
}
}