一般java web开发的程序员,都有一个共同的体会,接受请求参数都会使用一个vo类,这个vo类里封装了所有需要接受的参数,然后对参数进行业务逻辑处理,处理完后会持久化处理,通常每个业务表都会对应一个bean类,然后就需要将vo对象转化为bean对象再持久化,这个过程中,就需要new bean对象,给bean对象里的每个属性赋值;请求处理完,还需要有返回,通常返回也会封装一个vo类,所以也需要new一个vo对象,将需要返回的数据封装在这个vo对象里,这个是比较麻烦的。
使用MapStruct可以快速帮你解决vo->bean,bean->vo的转换工作,使得代码更加简洁。
这里使用JDK8,idea来编写程序,maven解决依赖,先在pom文件引入依赖:
<properties>
<org.mapstruct.version>1.2.0.Final</org.mapstruct.version>
</properties>
<!-- 省略其他.. -->
<dependencies>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>${org.mapstruct.version}</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${org.mapstruct.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${org.mapstruct.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
下面看java代码,先定义一个接口或者抽象类
@Mapper
public interface CarMapper {
CarMapper INSTANCE = Mappers.getMapper(CarMapper.class);
CarDto carToCarDto(Car car);
@Mappings({
@Mapping(source = "numberOfSeats", target = "seatCount")
})
CarDto carToCarDtoSpecial(Car car);
}
public class Car {
private String make;
private int numberOfSeats;
private CarType type;
private Date createTime;
//getter and setter...
}
public class CarDto {
private String make;
private int seatCount;
private String type;
private String date;
//getter and setter...
}
首先我们看mapstruct生成carToCarDto方法
public CarDto carToCarDto(Car car) {
if ( car == null ) {
return null;
}
CarDto carDto = new CarDto();
carDto.setMake( car.getMake() );
if ( car.getType() != null ) {
carDto.setType( car.getType().name() );
}
return carDto;
}
按照默认情况来说,mapstruct是根据两个对象里相同名称的属性名来进行赋值的,上面可以看出Car和CarDto有make和type两个属性名称是相同的,所以会将Car对象的两个属性值分别赋值给CarDto对象,当然也可以根据指定的属性来进行赋值。
carToCarDtoSpecial方法就是可以解决上面这个问题的,下面是mapstruct生成的源码
public CarDto carToCarDtoSpecial(Car car) {
if ( car == null ) {
return null;
}
CarDto carDto = new CarDto();
carDto.setSeatCount( car.getNumberOfSeats() ); //A处
carDto.setMake( car.getMake() );
if ( car.getType() != null ) {
carDto.setType( car.getType().name() );
}
return carDto;
}
源码多了A处,因为我们指定了注解
@Mapping(source = "numberOfSeats", target = "seatCount")
就是告诉mapstruct,Car的numberOfSeats属性值映射到CarDto的seatCount的属性值。
使用mapstruct来转换Car和CarDto是非常简单的
CarDto carDto = CarMapper.INSTANCE.carToCarDto(car);
CarDto carDto1 = CarMapper.INSTANCE.carToCarDtoSpecial(car);
所以就两行代码就针对两种情况,使用非常简洁。
上面只是一个Car对象转换到一个CarDto,mapstruct还可以将多个对象作为入参,转换到一个返回对象里。