数据实体转换MapStruct常用点

简介: MapStruct

在代码开发过程中,大型系统进行微服务化拆分,各个核心模块也会进行必要的业务代码分层,层与层之间参数传导过程中,各参数实体对像的属性传递等也变得越来越重要,这个过程中,大量的套路式代码get/set等也会出现在属性传递过程中,mapstruct即为解决这部分套路式代码提供了良好的解决方案,实际使用过程中,定议基于target/source的接口,同时添加不同属性名的映射,即可在编译过程中自动生成对应的实现,极大的简化了操作

 

MAVEN依赖

<dependency>
   <
groupId>org.mapstruct</groupId>
   <
artifactId>mapstruct-jdk8</artifactId>
   <
version>1.2.0.Final</version>
</
dependency>

<
dependency>
   <
groupId>org.mapstruct</groupId>
   <
artifactId>mapstruct-processor</artifactId>
   <
version>1.2.0.Final</version>
</
dependency>

 

 

测试Demo

测试目录结构


 

基本对像

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class School {
    private String schoolName; 
    private Student st;
} 
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
  public class Student {
    private String name; 
    private int age;
  }
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
  public class SchoolDO {
    private String schoolName;
    private StudentDO stNew;
  }
 
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
  public class StudentDO {
    private String name;
    private int newAge;
  }

 

 

通用方式-1

使用基础的泛型接口,实际接口直接继承泛型接口使用

l  字段属性名一致情况下无需再额外定义转换函数

l  如有字段属性名不一致,仅需重载单条记录的转换函数,同时添加map映射source/target的属性名

l  Eg: StudentConvert, 仅一个简单接口即实现了数据的转换,属性名也作了映射

public interface BasicMapper<SOURCE, TARGET> {
    /**
     * @Mappings({
     * @Mapping(source = "code", target = "newCode"),
     * @Mapping(source = "name", target = "newName")
     * })
     */
    @Mappings({})
    @InheritConfiguration
    TARGET to(SOURCE source);  

    @InheritConfiguration
    List<TARGET> to(Collection<SOURCE> source);  
   
@InheritInverseConfiguration     SOURCE from(TARGET source);
   
@InheritInverseConfiguration     List<SOURCE> from(Collection<TARGET> source); }
 
@Component
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface StudentConvert extends BasicMapper<Student, StudentDO>{
    
@Mappings({      @Mapping(source = "age", target = "newAge")      })      StudentDO to(Student source); } 
public static void main(String[] args) {
    SpringApplication.run(StructTest.class, args);
    ApplicationContext context = SpringUtil.getApplicationContext();
    StudentConvert stConvert = context.getBean(StudentConvert.class);
    /**
 * 实际转换中直接可单条或是多条list记录,并且有属性名不一致也可以
 * mapper接口中指定
 */
    Student st = Student.builder().name("student").age(18).build();
    Student st2 = Student.builder().name("student2").age(180).build();
    List<Student> stList = Lists.newArrayList(st, st2); 
    List<StudentDO> stDos = stConvert.to(stList);
    System.out.println(stDos.toString());
}
 

 


 

 

通用方式-2

嵌套转换

l  对像本身要作属性的映射转换

l  对像内某些属性也需作属生的映射转换

定议外层的映射接口,在接口中直接指定该属性对像的转换类,如下School对像中的student属性也要作相应的属性转换,可接口中直接指定 uses = {StudentConvert.class}:

@Component
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE, uses = {StudentConvert.class})
public interface SchoolConvert {      @Mappings({          @Mapping(source = "st", target = "stNew")      })      SchoolDO to(School source); }
 
@SpringBootApplication
  public class StructTest { 
   
public static void main(String[] args) {         SpringApplication.run(StructTest.class, args);         ApplicationContext context = SpringUtil.getApplicationContext();    
       
//demo 2         SchoolConvert schoolConvert = context.getBean(SchoolConvert.class);
       
School school = School.builder().schoolName("school-1").st(st).build();
       
SchoolDO schDO = schoolConvert.to(school);
       
System.out.println(schDO);
   
}
}
 

 

 

 

 

通用方式-3

l  Source对像中的属性对像中的属性转target属性

l  target对像中的属性对像中的属性转source属性

l  表达式取值(枚举类/常量)

l  调用自定义函数取值映射

 

@Mappings(
        @Mapping(source = "orderItem.discountInfo", target = "discountInfo")
)
ItemDetailDto order2itemdetail(OrderBaseDto orderBaseDto);
 @Mappings({
       
@Mapping(target = "materialId",source = "giftDetail.materialId")})
DemoDto command2ToDto(DemoCommand demoCommand);
 
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE,
imports = {TypeEnum.class})
public interface CampaignInputConvert {
  
    @Mappings({         
           
@Mapping(target ="giftType",expression = "java(TypeEnum.ITEM_NO.code()"),                     
           
@Mapping(target = "media",expression = "java(CommonConsts.SEND_MEDIA)")         
    })
   
GiftDemoBaseDto goodsDetailToGiftRpc(GoodsDemoOutput goodsDemoOutput, CustDemoOutput custDemoOutput, CustDemoDO custDemoDO);
 
@Component
@Mapper
(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface DemoInfoConvert {
   
List<DemoInfo> discntInfoDtoList2DemoInfoList(List<DemoInfoDto> demoInfoDtos);
   
@Mappings({
      
@Mapping(target = "discountValue", expression = "java(getDemotValue(discntInfoDto))")
    })
   
CouponInfo dto2output(DiscntInfoDto discntInfoDto);
    default
Long getDemoValue(DemoInfoDto demoInfoDto) {
       
if (discntInfoDto.getDiscountValue() != null) {
           
return discntInfoDto.getDiscountValue();
       
} else {
           
return discntInfoDto.getReduceValue();
       
}
    }
}

 

 

相关文章
|
SQL 存储 缓存
Mybatis的一级缓存,二级缓存过期时间分析
Mybatis的一级缓存,二级缓存过期时间分析
1215 0
|
9月前
|
缓存 Windows
彻底卸载软件且不留痕!卸载+清理+启动项优化,彻底清理残留信息
一款小巧高效的卸载工具,仅3.85M,主打彻底清理软件残留文件、注册表、服务等。支持强制卸载、应用商店程序移除、浏览器扩展管理、注册表清理、垃圾文件扫描及空文件夹清理,并提供文件粉碎、快捷方式修复等功能,界面简洁且可换肤,是系统清理的得力助手。
1440 6
|
Linux 缓存
CENTOS7更换YUM源为163源
访问地址为:http://mirrors.163.com/.help/centos.html 首先备份源: mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup 备份之前的源BASE,进入对应目录。
5174 0
|
人工智能 小程序 搜索推荐
分享5款让电脑更加有趣的小工具
介绍几款实用电脑小工具,提升工作学习效率:1) EmEditor,高效文本编辑器,支持大文件处理和语法高亮;2) QTTabBar,增强版Windows文件管理器,提供多标签页操作;3) 3171.cn,在线AI工具箱,集多种办公学习工具于一身;4) CrystalDiskInfo,硬盘健康监测,预防数据丢失;5) Deskreen,屏幕共享软件,适用于远程协作。推荐大家根据需要自行搜索下载使用。
701 1
|
SQL 监控 数据可视化
【高效编码】IDEA的常用插件(二)!!!,非常实用(DataBase,VisualVM Launcher等等)
您好,我是码农飞哥,感谢您阅读本文!如果此文对您有所帮助,请毫不犹豫的一键三连吧。上一篇我们介绍了Idea中几个常用插件,这篇文章,我们接着来介绍比较常见好用的插件。话不多说,直接进入主题。
1012 0
【高效编码】IDEA的常用插件(二)!!!,非常实用(DataBase,VisualVM Launcher等等)
|
机器学习/深度学习 人工智能 算法
2024年,计算机相关专业还值得选择吗?
2024年,计算机相关专业还值得选择吗?
|
存储 安全 关系型数据库
4个MySQL优化工具AWR,帮你准确定位数据库瓶颈!
4个MySQL优化工具AWR,帮你准确定位数据库瓶颈!
924 0
|
存储 弹性计算 数据库
2024年阿里云优惠券领取、使用教程及常见问题整理总结
随着云计算技术的不断发展,越来越多的企业和个人选择将业务迁移到云端。阿里云作为国内领先的云服务提供商,为用户提供了丰富的产品和服务。为了帮助用户降低成本,阿里云推出了优惠券活动,本文将为大家介绍阿里云优惠券的领取、使用方法以及常见问题解答。
1851 0
|
存储 弹性计算 大数据
阿里2核4G配置云服务器价格多少钱?阿里云2核4G云服务器531元一年怎么样?
随着云计算技术的日益发展,越来越多的企业和个人开始选择云服务器来满足其数据存储和处理需求。在众多的云服务提供商中,阿里云以其卓越的性能和稳定的服务赢得了广大用户的青睐。 近期,阿里云推出了一系列爆款特惠活动,其中一款2核4G通用算力型u1实例云服务器ECS备受关注。这款云服务器不仅拥有强大的计算能力,还提供了稳定的运行环境,非常适合对性能和稳定性有一定要求的用户。
384 0