@Mapper注解基于mapStract 框架实现对象转换:MapStract java bean 属性转换映射
引用转自:org.mapstruct:mapstruct 包(@Mapper、@Mapping)的使用
依赖包:
<!--mapStruct依赖-->
<dependency><groupId>org.mapstruct</groupId><artifactId>mapstruct</artifactId><version>1.3.1.Final</version>
</dependency>
<dependency><groupId>org.mapstruct</groupId><artifactId>mapstruct-processor</artifactId><version>1.3.1.Final</version><scope>provided</scope>
</dependency><!--编译插件-->
<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>1.3.1.Final</version></path></annotationProcessorPaths></configuration></plugin></plugins>
</build>
常用注解:
注解 | 使用位置 | 描述 |
Mapper | 适用在 类 接口 枚举 上 | 进行类的映射 |
Mapping | 适用在 方法 上 | 进行方法参数属性的映射 |
MapMapping | 适用在 方法 上 | 进行方法参数(Map类型)的映射 |
Mappings | 适用在 方法 上 | 组合注解,可以标记多个Mapping |
案例:
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface LogMapper {@Mappings({@Mapping(source = "id", target = "idDTO"),@Mapping(source = "realName", target = "realNameDTO"),@Mapping(source = "name", target = "nameDTO"),// 使用defaultValue@Mapping(target = "defaultValue", defaultValue = "morenzhi"),// 使用ignore@Mapping(target = "ignoreValue", ignore = true)})LogDTO convertToDTO(Log log);@Mappings({@Mapping(source = "idDTO", target = "id"),@Mapping(source = "realNameDTO", target = "realName"),@Mapping(source = "nameDTO", target = "name"),// 使用constant@Mapping(target = "address", constant = "1111"),// 使用ignore@Mapping(target = "ignoreValue", ignore = true)})Log covertToDO(LogDTO logDTO);// 有多个参数的时候,我们可以通过 参数.属性 的方式进行转换@Mappings({@Mapping(source = "log.id", target = "idDTO"),@Mapping(source = "log2.realName", target = "realNameDTO"),@Mapping(source = "log.name", target = "nameDTO"),})LogDTO convertToDTO2(Log log , Log2 log2);}//时间类型转换示例
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface LogMapper {@Mappings({@Mapping(source = "id", target = "idDTO"),@Mapping(source = "realName", target = "realNameDTO"),@Mapping(source = "name", target = "nameDTO"),// dateFormat :符合SimpleDataFormat的处理格式@Mapping(source = "dateStr", target = "date", dateFormat = "yyyy-MM-dd yy:mm:ss"),// numberFormat:符合DecimalFormat的处理格式@Mapping(source = "numberStr" , target = "number" , numberFormat = "$#.00")})LogDTO convertToDTO(Log log);}