-
不同的convert解决方案
名字 | 描述 |
---|---|
mapstruct | 基于jsr269实现在编译期间生成代码,性能高,精细控制,解耦 |
orika | 能够精细控制,解耦 |
org.springframework.beans.BeanUtils体系 | 简单易用,不能对属性进行定制处理 |
- 自己编写conver,需写大量的代码
/**
* 测试传统的通过getter和setter赋值完成pojo之间转换
* CarDto-->CarVo
*/
@Test
public void test1() {
// 模拟业务构造出的CarDTO对象
CarDTO carDTO = buildCarDTO();
// 转化dto-vo
CarVO carVO = new CarVO();
carVO.setId(carDTO.getId());
carVO.setVin(carDTO.getVin());
carVO.setPrice(carDTO.getPrice()); // 装箱拆箱机制,不需要我们自己转化
double totalPrice = carDTO.getTotalPrice();
DecimalFormat df = new DecimalFormat("#.00");
String totalPriceStr = df.format(totalPrice);
carVO.setTotalPrice(totalPriceStr);
Date publishDate = carDTO.getPublishDate();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String publishDateFormat = sdf.format(publishDate);
carVO.setPublishDate(publishDateFormat);
carVO.setBrandName(carDTO.getBrand());
List<PartDTO> partDTOS = carDTO.getPartDTOS();
boolean hasPart = partDTOS != null && !partDTOS.isEmpty();
carVO.setHasPart(hasPart);
DriverVO driverVO = new DriverVO();
DriverDTO driverDTO = carDTO.getDriverDTO();
driverVO.setDriverId(driverDTO.getId());
driverVO.setFullName(driverDTO.getName());
carVO.setDriverVO(driverVO);
System.out.println(carVO);
}
/**
* 模拟业务构造出的CarDTO对象
*/
private CarDTO buildCarDTO() {
CarDTO carDTO = new CarDTO();
carDTO.setId(330L);
carDTO.setVin("vin123456789");
carDTO.setPrice(123789.126d);
carDTO.setTotalPrice(143789.126d);
carDTO.setPublishDate(new Date());
carDTO.setColor("白色");
carDTO.setBrand("大众");
// 零件
PartDTO partDTO1 = new PartDTO();
partDTO1.setPartId(1L);
partDTO1.setPartName("多功能方向盘");
PartDTO partDTO2 = new PartDTO();
partDTO2.setPartId(2L);
partDTO2.setPartName("智能车门");
List<PartDTO> partDTOList = new ArrayList<>();
partDTOList.add(partDTO1);
partDTOList.add(partDTO2);
carDTO.setPartDTOS(partDTOList);
// 设置驾驶员
DriverDTO driverDTO = new DriverDTO();
driverDTO.setId(88L);
driverDTO.setName("小明");
carDTO.setDriverDTO(driverDTO);
return carDTO;
}
- 使用MapStruct转换
# 引入依赖
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>${mapstruct.version}</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct.version}</version>
</dependency>
# 编写convert
import org.mapstruct.factory.Mappers;
import java.util.List;
@Mapper
public abstract class CarConvert {
public static CarConvert INSTANCE = Mappers.getMapper(CarConvert.class);
public abstract List<CarVO> dtos2vos(List<CarDTO> carDTO);
}
# 测试
@Test
public void test2() {
CarDTO carDTO = buildCarDTO();
CarVO carVO = CarConvert.INSTANCE.dto2vo(carDTO);
System.out.println(carVO);
}
标签:driverDTO,carDTO,MapStruct,CarDTO,mapstruct,carVO,使用,new
From: https://www.cnblogs.com/chniny/p/16749558.html