通常对象与对象之间的互相转换,会通过专门转换的工具,个人比较喜欢使用mapstruct。
mapstruct属于属性映射工具,只需要定义一个 Mapper 接口,mapstruct 就会自动实现这个映射接口,避免了复杂繁琐的映射实现。官网地址
官网文档里对于简单转换的例子:
那么如何定制比较复杂的转换呢?
比方说根据编码拿到中文名
@Mapper
public interface PlatformConvert {
PlatformConvert INSTANCE = Mappers.getMapper(PlatformConvert.class);
@Mapping(target = "regionName", source = "regionCode", qualifiedByName = "regionCode2RegionName")
PlatformRespVO convert(PlatformDO o);
@Named("regionCode2RegionName")
default String format(Integer regionCode) {
return AreaUtils.format(regionCode, "-");
}
PlatformDO convert(PlatformAddReqVO reqVO, String appId, String appSecret);
PlatformUpdateReqDTO convert(PlatformUpdateReqVO reqVO, Long id);
PlatformUpdateReqDTO convert(PlatformUpdateStatusReqVO reqVO, Long id);
PlatformDO convert(PlatformUpdateReqDTO dto);
}
该Java函数定义了两个方法:
1.convert 方法:将 PlatformDO 对象转换为 PlatformRespVO 对象,并通过 regionCode2RegionName 方法别名将 regionCode 转换为 regionName。
2.format 方法(给了个别名regionCode2RegionName):根据 regionCode 获取对应的区域名称,使用 AreaUtils.format 方法格式化区域代码,分隔符为 -。
另外:如果需要通过入参的方式将列表转换到类中,只需要保证入参的列表名和类中的列表名一样即可
如:类中的列表字段名为list,那么只需要将convert入参的列表字段名也改成list,就会自动转换