介绍
- 处理对象映射的解决方案
-
解决在分层应用中(Entity->Dto,Dto->Entity),进行数据转换而产生的冗余工作
依赖
org.mapstruct
mapstruct
---
# 使用
1. 使用`@Mapper`注解标识一个接口为MapStruct
2. 编写映射方法
3. 注入映射器使用
---
# 注解
## @Mapper
- 标识一个接口是映射器
- 属性:
- `String componentModel`: 定义生成的Mapper实现类如何被Spring容器管理
- `spring`: 自动注入到Spring容器
- `default`: 默认,通过静态工厂方法获取实例(`Mappers.getMapper(Clazz)`)
- `String unmappedTargetPolicy`: 定义目标对象没有对应映射源时采取的行为
- `ReportingPolicy.ERROR`: 编译失败
- `ReportingPolicy.WARN`: 发出警告
- `ReportingPolicy.IGNORE`: 忽略未映射的属性
## @Mapping
- 当映射属性名与类型不同时的显式映射
- 属性:
- `String source`: 原对象属性名
- `String target`: 目标对象属性名
---
# 方法
- `D toDto(E entity)`
- `E toEntity(D dto)`
- `List
<D> toDtoList(List<E> list)`
- `List
<E> toEntityList(List<D> list)`