Mapstruct 是一个很好用的插件用来处理java工程中实体间的转换,比如po转vo,domain转dto。
通常我们会写一些convert 写一堆set get来处理这个转换,现在我们可以使用Mapstruct 。
http://mapstruct.org/这是mapstruct的官网
https://github.com/mapstruct/mapstruct-examples这是官网推荐的一些demo
下面开始配置
首先pom
版本号
<properties>
<org.mapstruct.version>1.1.0.Final</org.mapstruct.version>
</properties>
依赖部分
<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>
<scope>provided</scope>
</dependency>
这样配置就算完成了
下面是使用部分
domian
public class Car {
private String make;
private int numberOfSeats;
private CarType type;
}
dto
public class CarDto {
private String make;
private int seatCount;
private String type;
//constructor, getters, setters etc.
}
这是你想要互转的两个实体domian与dto
@Mapper
public interface CarMapper {
CarMapper INSTANCE = Mappers.getMapper( CarMapper.class );
@Mapping(source = "numberOfSeats", target = "seatCount")
CarDto carToCarDto(Car car);
}
@Mapping(source = "numberOfSeats", target = "seatCount")
指把在car向cardtocar进行转换的时候把car的numberofseats的值赋给cardto的seatcount字段,其他的同名字段会自动赋值
使用CarDto cardto= CarMapper .INSTANCE.carToCarDto(car);
如果多个转换
@Mappings({
@Mapping(source = "make", target = "manufacturer"),
@Mapping(source = "numberOfSeats", target = "seatCount")
})
上面的例子来自官网http://mapstruct.org/
一下是一些mapstruct教程
http://www.tianshouzhi.com/api/tutorials/mapstruct/291
http://www.tuicool.com/articles/2mIRRjn
ps:一部分使用eclipse的会发现转换mapper的实现类不存在,或者说不能自动生成,是因为m2e的原因,详情及解决方案见我的另一篇博文