日常开发中,我们时长会写很多关于PO转VO的代码或者是VO转DTO相关的代码,造成我们的程序异常的臃肿。
如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static ParkinglotVO DTOcastToVO(ParkinglotDTO parkinglotDTO) {
ParkinglotVO parkinglotVO = new ParkinglotVO();
parkinglotVO.address = parkinglotDTO.getContent().getName().getAddress();
parkinglotVO.distance = parkinglotDTO.getDistance().getValue();
parkinglotVO.lat = parkinglotDTO.getContent().getName().getLat();
parkinglotVO.lon = parkinglotDTO.getContent().getName().getLon();
parkinglotVO.parkinglotId = parkinglotDTO.getContent().getName().getParkinglotId();
parkinglotVO.isReservation = parkinglotDTO.getContent().getName().getIsReservation();
parkinglotVO.parkinglotName = parkinglotDTO.getContent().getName().getParkinglotName();
parkinglotVO.totalPlaces = parkinglotDTO.getContent().getName().getTotalPlaces();
parkinglotVO.isSupportAgv = parkinglotDTO.getContent().getName().getIsSupportAgv();
parkinglotVO.isSpaceSearch = parkinglotDTO.getContent().getName().getIsSpaceSearch();
parkinglotVO.photo = parkinglotDTO.getContent().getName().getPhoto();
parkinglotVO.photoMin = parkinglotDTO.getContent().getName().getPhotoMin();
parkinglotVO.isSupportCharging = parkinglotDTO.getContent().getName().getIsSupportCharging();
parkinglotVO.chargingNum = parkinglotDTO.getContent().getName().getChargingNum();
parkinglotVO.isSub = parkinglotDTO.getContent().getName().getIsSub();
parkinglotVO.isSupportNormal=parkinglotDTO.getContent().getName().getIsSupportNormal();
return parkinglotVO;
}

编写这种代码即耗时,有没有什么营养,但是又不能不写。
Spring和Apache给我们提供了BeatUtils工具了,可以通过

1
2
3
public static void copyProperties(Object source, Object target) throws BeansException {
copyProperties(source, target, null, (String[]) null);
}

实现对象之间属性的拷贝,但是这种方式缺点也很明显,他的实现机制是通过反射,导致拷贝属性的花费时间较长,性能很低。“阿里巴巴编码规范”也有提尽量避免使用BeanUtils工具。

img

使用MapStruct

MapStruct很优雅的帮我们解决了这个问题。

MapStruct

官网: https://mapstruct.org/
github: https://github.com/mapstruct/mapstruct
文档:https://mapstruct.org/documentation/stable/reference/html/

使用mapStruct

确保你的jdk版本是java8或者更高

引入依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<properties>
<mapstruct.version>1.3.1.Final</mapstruct.version>
</properties>
<dependencies>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>${mapstruct.version}</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>${mapstruct.version}</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct.version}</version>
</dependency>
</dependencies>

准备几个实体类

  1. Person
1
2
3
4
5
@Data
public class Person {
private Integer age;
private String fullname;
}
  1. PersonDTO
1
2
3
4
5
@Data
public class PersonDTO {
private Integer age;
private String name;
}
  1. Engine
1
2
3
4
5
@Data
public class Engine {
private Integer horsePower;
private Integer fuel;
}
  1. EngineDTO
1
2
3
4
5
@Data
public class EngineDTO {
private Integer horsePower;
private Integer fuel;
}
  1. Car
1
2
3
4
5
6
@Data
public class Car {
private Integer make;
private Integer numberOfSeats;
private Engine engine;
}
  1. CarDTO
1
2
3
4
5
6
7
@Data
public class CarDTO {
private Integer manufacturer;
private Integer seatCount;
private EngineDTO engine;
private PersonDTO person;
}

定义一个映射器

注意此处使用的注解全都是org.mapstruct不要引错。

1
2
3
4
5
6
7
8
9
10
@Mapper
public interface CarMap {

@Mapping(source = "make", target = "manufacturer")
@Mapping(source = "numberOfSeats", target = "seatCount")
CarDTO carToCarDto(Car car);

@Mapping(source = "fullname", target = "name")
PersonDTO personToPersonDto(Person person);
}

如果你的DTO和实体类中的字段名称是一致的,只需要写方法签名即可,不需要写任何代码。
如果参数名称有变化,需要使用@Maping注解,source为原参数名称,target为转换后的类的参数名称。
编译后,会在同级目录生成实现类,如下:

img

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
@Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2020-08-18T19:50:47+0800",
comments = "version: 1.3.1.Final, compiler: javac, environment: Java 1.8.0_241 (Oracle Corporation)"
)
public class CarMapImpl implements CarMap {

@Override
public CarDTO carToCarDto(Car car) {
if ( car == null ) {
return null;
}

CarDTO carDTO = new CarDTO();

carDTO.setSeatCount( car.getNumberOfSeats() );
carDTO.setManufacturer( car.getMake() );
carDTO.setEngine( engineToEngineDTO( car.getEngine() ) );

return carDTO;
}

@Override
public PersonDTO personToPersonDto(Person person) {
if ( person == null ) {
return null;
}

PersonDTO personDTO = new PersonDTO();

personDTO.setName( person.getFullname() );
personDTO.setAge( person.getAge() );

return personDTO;
}

protected EngineDTO engineToEngineDTO(Engine engine) {
if ( engine == null ) {
return null;
}

EngineDTO engineDTO = new EngineDTO();

engineDTO.setHorsePower( engine.getHorsePower() );
engineDTO.setFuel( engine.getFuel() );

return engineDTO;
}
}

多个源参数的映射方法

dto的类中,CarDTO的属性=Car+Person的属性,这难不倒mapStruct他支持传递多个源数据。

1
2
3
@Mapping(source = "car.make", target = "manufacturer")
@Mapping(source = "car.numberOfSeats", target = "seatCount")
CarDTO carToCarDto(Car car,Person person);

值得注意的是,我们@Mapping中写的映射此时需要指定那个对象的,使用对象名.属性名
编译后结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public CarDTO carToCarDto(Car car, Person person) {
if ( car == null && person == null ) {
return null;
}
CarDTO carDTO = new CarDTO();
if ( car != null ) {
carDTO.setSeatCount( car.getNumberOfSeats() );
carDTO.setManufacturer( car.getMake() );
carDTO.setEngine( engineToEngineDTO( car.getEngine() ) );
}
if ( person != null ) {
carDTO.setPerson( personToPersonDto( person ) );
}
return carDTO;
}

向映射器添加自定义方法

在某些情况下,可能需要手动实现从一种类型到另一种类型的特定映射,而MapStruct无法生成这种映射。解决此问题的一种方法是在另一个类上实现自定义方法,然后该类由MapStruct生成的映射器使用。
eg: 手动编写Person属性映射

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Mapper
public interface CarMap {

@Mapping(source = "car.make", target = "manufacturer")
@Mapping(source = "car.numberOfSeats", target = "seatCount")
CarDTO carToCarDto(Car car,Person person);

default PersonDTO personToPersonDto(Person person){
if(Objects.isNull(person)){
return null;
}
PersonDTO personDTO = new PersonDTO();
personDTO.setName(person.getFullname());
personDTO.setAge(person.getAge());
return personDTO;
}

}

编译后的实现类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
@Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2020-08-18T20:05:05+0800",
comments = "version: 1.3.1.Final, compiler: javac, environment: Java 1.8.0_241 (Oracle Corporation)"
)
public class CarMapImpl implements CarMap {

@Override
public CarDTO carToCarDto(Car car, Person person) {
if ( car == null && person == null ) {
return null;
}

CarDTO carDTO = new CarDTO();

if ( car != null ) {
carDTO.setSeatCount( car.getNumberOfSeats() );
carDTO.setManufacturer( car.getMake() );
carDTO.setEngine( engineToEngineDTO( car.getEngine() ) );
}
if ( person != null ) {
carDTO.setPerson( personToPersonDto( person ) );
}

return carDTO;
}

protected EngineDTO engineToEngineDTO(Engine engine) {
if ( engine == null ) {
return null;
}

EngineDTO engineDTO = new EngineDTO();

engineDTO.setHorsePower( engine.getHorsePower() );
engineDTO.setFuel( engine.getFuel() );

return engineDTO;
}
}

嵌套映射

改一下CarDTO,将Engine的属性直接暴露在CarDTO里面,此时原Car对象中Engine是已对象的形式存在。我们可以通过@Mapping手动指定字段映射

1
2
3
4
5
6
7
8
9
@Data
public class CarDTO {
private Integer manufacturer;
private Integer seatCount;
private Integer horsePower;
private Integer fuel;
// private EngineDTO engine;
private PersonDTO person;
}

通过对象名.属性的形式指定映射

1
2
3
4
5
@Mapping(source = "engine.horsePower", target = "horsePower")
@Mapping(source = "engine.fuel", target = "fuel")
@Mapping(source = "make", target = "manufacturer")
@Mapping(source = "numberOfSeats", target = "seatCount")
CarDTO carToCarDto(Car car);

编译后结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public CarDTO carToCarDto(Car car) {
if ( car == null ) {
return null;
}

CarDTO carDTO = new CarDTO();

carDTO.setHorsePower( carEngineHorsePower( car ) );
carDTO.setSeatCount( car.getNumberOfSeats() );
carDTO.setFuel( carEngineFuel( car ) );
carDTO.setManufacturer( car.getMake() );

return carDTO;
}

private Integer carEngineHorsePower(Car car) {
if ( car == null ) {
return null;
}
Engine engine = car.getEngine();
if ( engine == null ) {
return null;
}
Integer horsePower = engine.getHorsePower();
if ( horsePower == null ) {
return null;
}
return horsePower;
}

private Integer carEngineFuel(Car car) {
if ( car == null ) {
return null;
}
Engine engine = car.getEngine();
if ( engine == null ) {
return null;
}
Integer fuel = engine.getFuel();
if ( fuel == null ) {
return null;
}
return fuel;
}

更新现有的Bean实例

在某些情况下,您需要的映射不会创建目标类型的新实例,而是更新该类型的现有实例。可以通过为目标对象添加一个参数并将其标记为来实现这种映射@MappingTarget

1
2
3
@Mapping(target = "make", source = "manufacturer")
@Mapping(target = "numberOfSeats", source = "seatCount")
void updateCarFromDto(CarDTO carDTO,@MappingTarget Car car);

编译后

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@Override
public void updateCarFromDto(CarDTO carDTO, Car car) {
if ( carDTO == null ) {
return;
}

car.setMake( carDTO.getManufacturer() );
car.setNumberOfSeats( carDTO.getSeatCount() );
if ( carDTO.getEngine() != null ) {
if ( car.getEngine() == null ) {
car.setEngine( new Engine() );
}
engineDTOToEngine( carDTO.getEngine(), car.getEngine() );
}
else {
car.setEngine( null );
}
}

protected void engineDTOToEngine(EngineDTO engineDTO, Engine mappingTarget) {
if ( engineDTO == null ) {
return;
}

mappingTarget.setHorsePower( engineDTO.getHorsePower() );
mappingTarget.setFuel( engineDTO.getFuel() );
}

该updateCarFromDto()方法生成的代码将Car使用给定CarDTO对象的属性更新传递的实例。可能只有一个参数标记为映射目标。代替void您也可以将方法的返回类型设置为目标参数的类型,这将导致生成的实现更新传递的映射目标并返回它。这样可以流畅地调用映射方法。

使用映射器

直接使用

1
2
3
4
@Mapper
public interface CarMap {
CarMap CAR_MAP = Mappers.getMapper(CarMap.class);
}

整合Spring

设置componentModel = "spring",需要使用的地方直接通过@Resource注入即可

1
2
3
4
@Mapper(componentModel = "spring")
public interface CarMap {
...
}

数据类型转换

隐式类型转换

在许多情况下,MapStruct会自动处理类型转换。例如,如果某个属性int在源Bean中是类型但String在目标Bean中是类型,则生成的代码将分别通过分别调用String#valueOf(int)和来透明地执行转换Integer#parseInt(String)。

  • 之间的所有Java基本数据类型及其相应的包装类型,例如之间int和Integer,boolean和Boolean等生成的代码是null转换一个包装型成相应的原始类型时一个感知,即,null检查将被执行。
  • 在所有Java原语数字类型和包装器类型之间,例如在int和long或byte和之间Integer。

数字,日期 格式化

Car中新增price,createTime属性

1
2
3
4
5
6
7
8
9
@Data
public class Car {
private Integer make;
private Integer numberOfSeats;
private Engine engine;

private Integer price;
private LocalDateTime createTime;
}

Engine中horsePower类型替换为BigDecimal

1
2
3
4
5
@Data
public class Engine {
private BigDecimal horsePower;
private Integer fuel;
}

对应的EngineDTO和CarDTO如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Data
public class EngineDTO {
private String horsePower;
private Integer fuel;
}
@Data
public class CarDTO {
private Integer manufacturer;
private Integer seatCount;
private EngineDTO engine;
private PersonDTO person;
private String price;
private String createTime;
}

现在需要将price前面添加$前缀后面添加两位0,horsePower使用科学计数法,时间格式化的格式为yyyy-MM-dd HH:mm:ss

1
2
3
4
5
6
@Mapping(target = "engine.horsePower", source = "engine.horsePower", numberFormat = "#.##E0")
@Mapping(target = "price", source = "price", numberFormat = "$#.00")
@Mapping(target = "createTime", dateFormat = "yyyy-MM-dd HH:mm:ss")
@Mapping(source = "make", target = "manufacturer")
@Mapping(source = "numberOfSeats", target = "seatCount")
CarDTO updateCarFromDto(Car car);

编译后

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class CarMapImpl implements CarMap {

@Override
public CarDTO updateCarFromDto(Car car) {
if ( car == null ) {
return null;
}

CarDTO carDTO = new CarDTO();

carDTO.setEngine( engineToEngineDTO( car.getEngine() ) );
carDTO.setSeatCount( car.getNumberOfSeats() );
if ( car.getPrice() != null ) {
carDTO.setPrice( new DecimalFormat( "$#.00" ).format( car.getPrice() ) );
}
carDTO.setManufacturer( car.getMake() );
if ( car.getCreateTime() != null ) {
carDTO.setCreateTime( DateTimeFormatter.ofPattern( "yyyy-MM-dd HH:mm:ss" ).format( car.getCreateTime() ) );
}

return carDTO;
}

private DecimalFormat createDecimalFormat( String numberFormat ) {

DecimalFormat df = new DecimalFormat( numberFormat );
df.setParseBigDecimal( true );
return df;
}

protected EngineDTO engineToEngineDTO(Engine engine) {
if ( engine == null ) {
return null;
}

EngineDTO engineDTO = new EngineDTO();

if ( engine.getHorsePower() != null ) {
engineDTO.setHorsePower( createDecimalFormat( "#.##E0" ).format( engine.getHorsePower() ) );
}
engineDTO.setFuel( engine.getFuel() );

return engineDTO;
}
}

映射集合

1
2
3
4
5
6
@Mapper
public interface CarMapper {
Set<String> integerSetToStringSet(Set<Integer> integers);
List<CarDto> carsToCarDtos(List<Car> cars);
CarDto carToCarDto(Car car);
}

映射map

1
2
3
4
public interface SourceTargetMapper {
@MapMapping(valueDateFormat = "dd.MM.yyyy")
Map<String, String> longDateMapToStringStringMap(Map<Long, Date> source);
}

使用表达式

场景
有些时候需要使用自己写的方法对一些属性进行映射,比如VO中有一个map,需要转换的类中存储的是该map的json 字符串形式。

1
2
3
4
@Data
public class AddPassagewayParam {
private HashMap<String,Object> accessMap;
}
1
2
3
4
@Data
public class SmsPassageway implements Serializable {
// json字符串形式
private String accessMsg;

需要将map映射为json str
这时候我们借助“表达式”可以这样写

1
2
3
4
5
6
7
8
@Mapper(componentModel = "spring")
public interface SmsPassagewayMap {

@Mapping(target = "accessMsg",
expression = "java(com.jd.icity.tools.JsonHelper.object2Json(addPassagewayParam.getAccessMap()))"
)
SmsPassageway addPassagewayParam2SmsPassageway(AddPassagewayParam addPassagewayParam);
}