概述
-
MapStruct 可以将某几种类型的对象映射为另外一种类型,如将多个 DO(业务实体对象) 对象转换为 DTO(数据传输对象)
- 使用方式也很简单,定义一个映射接口,声明映射方法,配上注解,MapSturct 就会实现此接口
使用例子
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>1.2.0.CR1</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.2.0.CR1</version>
<scope>provided</scope>
</dependency>
----------商品信息----------
@Data
public class GoodInfo {
private Long id;
private String title;
private double price;
private int order;
private Long typeId;
}
----------商品类型----------
@Data
public class GoodType {
private Long id;
private String name;
private int show;
private int order;
}
@Data
public class GoodInfoDTO {
private String goodId;
private String goodName;
private double goodPrice;
private String typeName;
}
- 创建 Mapper(映射)接口,MapStruct 就会自动实现该接口
@Mapper(componentModel = "spring")
public interface GoodInfoMapper {
@Mappings({
@Mapping(source = "type.name",target = "typeName"),
@Mapping(source = "good.id",target = "goodId"),
@Mapping(source = "good.title",target = "goodName"),
@Mapping(source = "good.price",target = "goodPrice")
})
GoodInfoDTO fromGoodInfoDTO(GoodInfo good, GoodType type);
}
- 测试:将商品信息和商品类型通过 Mapper 映射成 GoodInfoDTO
@Autowired
private GoodInfoMapper goodInfoMapper;
@RequestMapping(value = "/detail/{id}")
public GoodInfoDTO details(@PathVariable("id")Long id){
GoodInfo goodInfo = goodInfoRepository.findOne(id);
GoodType goodType = goodTypeRepository.findOne(goodInfo.getId());
return goodInfoMapper.fromGoodInfoDTO(goodInfo,goodType);
}
MapStruct注解
-
@Mapper:注解在接口、类上,这样 MapStruct 才会去实现该接口
- componentModel:该属性用于指定实现类的类型,有几个属性:
- default:默认,不使用任何组建类型,可以通过Mappers.getMapper(Class) 方式获取实例对象
- spring:在实现类上注解 @Component,可通过 @Autowired 方式注入
- jsr330:实现类上添加@javax.inject.Named 和@Singleton注解,可以通过 @Inject注解获取。
-
@Mappings:配置多个@Mapping
-
@Mapping:配置属性映射,若源对象属性与目标对象名字一致,会自动映射对应属性
- source:源属性、target:目标属性
- dateFormat:可将 String 到 Date 日期之间相互转换,通过 SimpleDateFormat,该值为 SimpleDateFormat 的日期格式