1. 初识mapstruct
MapStruct是一个代码生成器,简化了不同的Java Bean之间映射的处理,所以映射指的就是从一个实体变化成一个实体。例如我们在实际开发中,DAO层的实体和一些数据传输对象(DTO),大部分属性都是相同的,只有少部分的不同,通过mapStruct,可以让不同实体之间的转换变的简单。我们只需要按照约定的方式进行配置即可。
MapStruct是一个可以处理注解的Java编译器插件,可以在命令行中使用,也可以在IDE中使用。MapStruct有一些默认配置,但是也为用户提供了自己进行配置的途径。
2. mapstruct的优点
与手动编写映射代码相比,MapStruct通过生成繁琐且易于出错的代码来节省时间。遵循配置方法上的约定,MapStruct使用合理的默认值,但在配置或实现特殊行为时不加理会。
与动态映射框架相比,MapStruct具有以下优点:
2.1 通过使用普通方法调用(settter/getter)而不是反射来快速执行
2.2 编译时类型安全性:只能映射相互映射的对象和属性,不能将order实体意外映射到customer DTO等。
如果有如下问题,编译时会抛出异常
(1) 映射不完整(并非所有目标属性都被映射)
(2) 映射不正确(找不到正确的映射方法或类型转换)
2.3 作为一个工具类,相比于手写, 具有更加便捷不易出错的特点。
3. mapstruct环境搭建
基于maven的项目,需要在pom.xml中增加mapstruct的依赖

增加lombok依赖

下载插件(非必须)

这个插件可以起一些辅助作用,方便开发,比如ctrl+鼠标左键即可跳转到参数对应的class
4. Mapstruct应用实践
通过一个bo实体与do实体之间相互转换举例。
Do实体:
public class SwitchEntity extends AbstractEntity{
protected static final String tableName = "switch";
@Id
@Column(name = "switch_id")
private String switchId;
@Column(name = "switch_name")
private String switchName;
@Column(name = "factory")
private String factory;
@Column(name = "device_model")
private String deviceModel;
@Column(name = "config_model")
private String configModel;
@Column(name = "resource_pool")
private String resourcePool;
@Column(name = "switch_as")
private Long switchAs;
@Column(name = "hostname")
private String hostname;
@Column(name = "manage_ip")
private String manageIp;
@Column(name = "login_port")
private String loginPort;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
@Column(name = "configure_port")
private String configurePort;
@Column(name = "vtep_vlan")
private String vtepVlan;
@Column(name = "vtep_ip")
private String vtepIp;
@Column(name = "resource_name")
private String resourceName;
@Column(name = "access_point")
private String accessPoint;
@Column(name = "resource_type")
private String resourceType;
@Column(name = "is_initialized")
private Boolean isInitialized;
@Column(name = "sys_mac")
private String sysMac;}
BO实体:
public class Switch {
private String switchId;
private String switchName;
private String factory;
private String deviceModel;
private String configModel;
private String resourcePool;
private String resourceName;
private String resourceType;
private Long switchAs;
private String hostname;
private String manageIp;
private String loginPort;
private String username;
private String pwd;
private String configurePort;
private String vtepVlan;
private String vtepIp;
private String sysMac;
private String accessPoint;
private Boolean isInitialized;
private String agentIp;
private String status;}
4.1. 定义一个映射器
要创建映射器,只需使用所需的映射方法定义一个Java接口,并用注释对其进行org.mapstruct.Mapper注释:
该@Mapper注释将使得MapStruct代码生成器创建的执行PersonMapper 过程中生成时的界面。
在生成的方法实现中,源类型(例如SwitchEntity)的所有可读属性都将被复制到目标类型(例如Switch)的相应属性中:
@Mapper
public interface SwitchConvertBasic {
SwitchConvertBasic covert = Mappers.getMapper(SwitchConvertBasic.class);
//SwitchEntity 转 switch
@Mappings({
@Mapping(target = "pwd", source = "password")
})
Switch toModel(SwitchEntity source);
//Switch 转 SwitchEntity
@Mappings({
@Mapping(target = "password",source = "pwd")
})
SwitchEntity toEntity(Switch source);
}
当一个属性与其目标实体对应的名称相同时,它将被隐式映射。
当属性在目标实体中具有不同的名称时,可以通过@Mapping注释指定其名称:
target:目标bean的属性名称;
source:源bean的属性名称
如果不指定@Mapping,默认映射name相同的field
如果映射的对象field name不一样,通过 @Mapping 指定。
忽略字段加@Mapping#ignore() = true
编译,查看生成的impl:
package com.ctcc.cda.entity.mapper.convert;
import com.ctcc.cda.entity.SwitchEntity;
import com.ctcc.cda.params.common.model.Switch;
import javax.annotation.Generated;
@Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2023-05-07T16:16:34+0800",
comments = "version: 1.2.0.Final, compiler: javac, environment: Java 1.8.0_161 (Oracle Corporation)"
)
public class SwitchConvertBasicImpl implements SwitchConvertBasic {
@Override
public Switch toModel(SwitchEntity source) {
if ( source == null ) {
return null;
}
Switch switch1 = new Switch();
switch1.setPwd( source.getPassword() );
switch1.setSwitchId( source.getSwitchId() );
switch1.setSwitchName( source.getSwitchName() );
switch1.setFactory( source.getFactory() );
switch1.setDeviceModel( source.getDeviceModel() );
switch1.setConfigModel( source.getConfigModel() );
switch1.setResourcePool( source.getResourcePool() );
switch1.setResourceName( source.getResourceName() );
switch1.setResourceType( source.getResourceType() );
switch1.setSwitchAs( source.getSwitchAs() );
switch1.setHostname( source.getHostname() );
switch1.setManageIp( source.getManageIp() );
switch1.setLoginPort( source.getLoginPort() );
switch1.setUsername( source.getUsername() );
switch1.setConfigurePort( source.getConfigurePort() );
switch1.setVtepVlan( source.getVtepVlan() );
switch1.setVtepIp( source.getVtepIp() );
switch1.setSysMac( source.getSysMac() );
switch1.setAccessPoint( source.getAccessPoint() );
switch1.setIsInitialized( source.getIsInitialized() );
return switch1;
}
@Override
public SwitchEntity toEntity(Switch source) {
if ( source == null ) {
return null;
}
SwitchEntity switchEntity = new SwitchEntity();
switchEntity.setPassword( source.getPwd() );
switchEntity.setSwitchId( source.getSwitchId() );
switchEntity.setSwitchName( source.getSwitchName() );
switchEntity.setFactory( source.getFactory() );
switchEntity.setDeviceModel( source.getDeviceModel() );
switchEntity.setConfigModel( source.getConfigModel() );
switchEntity.setResourcePool( source.getResourcePool() );
switchEntity.setSwitchAs( source.getSwitchAs() );
switchEntity.setHostname( source.getHostname() );
switchEntity.setManageIp( source.getManageIp() );
switchEntity.setLoginPort( source.getLoginPort() );
switchEntity.setUsername( source.getUsername() );
switchEntity.setConfigurePort( source.getConfigurePort() );
switchEntity.setVtepVlan( source.getVtepVlan() );
switchEntity.setVtepIp( source.getVtepIp() );
switchEntity.setResourceName( source.getResourceName() );
switchEntity.setAccessPoint( source.getAccessPoint() );
switchEntity.setResourceType( source.getResourceType() );
switchEntity.setIsInitialized( source.getIsInitialized() );
switchEntity.setSysMac( source.getSysMac() );
return switchEntity;
}
}
4.2.验证
在main函数中new 一个SwitchEntity对象并调用两个转换接口并打印经过转换得到的对象的属性值。
测试代码:
public static void main(String[] args) {
SwitchEntity switchEntity = SwitchEntity.builder()
.switchId(UUIDUtil.getUUID())
.switchName("test-sw")
.switchAs(1001L)
.configModel(Constant.CONFIG_MODEL_H3C)
.deviceModel(Constant.CONFIG_MODEL_H3C)
.loginPort("22")
.configurePort("80")
.hostname("xx-aa-bb")
.manageIp("123.10.36.99")
.password("******")
.username("admin")
.resourcePool("test-dc-001")
.resourceName("模拟资源池1")
.accessPoint("az1")
.vtepVlan("310")
.vtepIp("192.168.10.12/24")
.factory("新华三")
.resourceType("MAZ")
.isInitialized(true)
.build();
System.out.println("原始DO:\n"+switchEntity.toString());
Switch switchModel = covert.toModel(switchEntity);
System.out.println("DO转BO:\n"+switchModel.toString());
SwitchEntity switchEntity1 = covert.toEntity(switchModel);
System.out.println("BO转DO:\n"+switchEntity1.toString());
}
结果如下:
"C:\Program Files\Java\jdk1.8.0_161\bin\java.exe" com.ctcc.cda.entity.mapper.convert.SwitchConvertBasic
原始DO:
SwitchEntity(switchId=6e13158c-e143-4dde-92e4-5decad39e302, switchName=test-sw, factory=新华三, deviceModel=H3C, configModel=H3C, resourcePool=test-dc-001, switchAs=1001, hostname=xx-aa-bb, manageIp=123.10.36.99, loginPort=22, username=admin, password=******, configurePort=80, vtepVlan=310, vtepIp=192.168.10.12/24, resourceName=模拟资源池1, accessPoint=az1, resourceType=MAZ, isInitialized=true, sysMac=null)
DO转BO:
Switch(switchId=44117fe2-5c66-481c-8289-99aec13e6ed9, switchName=test-sw, factory=新华三, deviceModel=H3C, configModel=H3C, resourcePool=test-dc-001, resourceName=模拟资源池1, resourceType=MAZ, switchAs=1001, hostname=xx-aa-bb, manageIp=123.10.36.99, loginPort=22, username=admin, pwd=******, configurePort=80, vtepVlan=310, vtepIp=192.168.10.12/24, sysMac=null, accessPoint=az1, isInitialized=true, agentIp=null, status=null)
BO转DO:
SwitchEntity(switchId=44117fe2-5c66-481c-8289-99aec13e6ed9, switchName=test-sw, factory=新华三, deviceModel=H3C, configModel=H3C, resourcePool=test-dc-001, switchAs=1001, hostname=xx-aa-bb, manageIp=123.10.36.99, loginPort=22, username=admin, password=******, configurePort=80, vtepVlan=310, vtepIp=192.168.10.12/24, resourceName=模拟资源池1, accessPoint=az1, resourceType=MAZ, isInitialized=true, sysMac=null)
Process finished with exit code 0
可以看到初始化的do对象和经过两次转换得到的do和Bo对象各个属性值都相同,符合预期。
Covert接口生成的Impl实现类在target文件夹下:
package com.ctcc.cda.entity.mapper.convert;
import com.ctcc.cda.entity.SwitchEntity;
import com.ctcc.cda.params.common.model.Switch;
import javax.annotation.Generated;
@Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2023-05-07T16:27:52+0800",
comments = "version: 1.2.0.Final, compiler: javac, environment: Java 1.8.0_161 (Oracle Corporation)"
)
public class SwitchConvertBasicImpl implements SwitchConvertBasic {
@Override
public Switch toModel(SwitchEntity source) {
if ( source == null ) {
return null;
}
Switch switch1 = new Switch();
switch1.setPwd( source.getPassword() );
switch1.setSwitchId( source.getSwitchId() );
switch1.setSwitchName( source.getSwitchName() );
switch1.setFactory( source.getFactory() );
switch1.setDeviceModel( source.getDeviceModel() );
switch1.setConfigModel( source.getConfigModel() );
switch1.setResourcePool( source.getResourcePool() );
switch1.setResourceName( source.getResourceName() );
switch1.setResourceType( source.getResourceType() );
switch1.setSwitchAs( source.getSwitchAs() );
switch1.setHostname( source.getHostname() );
switch1.setManageIp( source.getManageIp() );
switch1.setLoginPort( source.getLoginPort() );
switch1.setUsername( source.getUsername() );
switch1.setConfigurePort( source.getConfigurePort() );
switch1.setVtepVlan( source.getVtepVlan() );
switch1.setVtepIp( source.getVtepIp() );
switch1.setSysMac( source.getSysMac() );
switch1.setAccessPoint( source.getAccessPoint() );
switch1.setIsInitialized( source.getIsInitialized() );
return switch1;
}
@Override
public SwitchEntity toEntity(Switch source) {
if ( source == null ) {
return null;
}
SwitchEntity switchEntity = new SwitchEntity();
switchEntity.setPassword( source.getPwd() );
switchEntity.setSwitchId( source.getSwitchId() );
switchEntity.setSwitchName( source.getSwitchName() );
switchEntity.setFactory( source.getFactory() );
switchEntity.setDeviceModel( source.getDeviceModel() );
switchEntity.setConfigModel( source.getConfigModel() );
switchEntity.setResourcePool( source.getResourcePool() );
switchEntity.setSwitchAs( source.getSwitchAs() );
switchEntity.setHostname( source.getHostname() );
switchEntity.setManageIp( source.getManageIp() );
switchEntity.setLoginPort( source.getLoginPort() );
switchEntity.setUsername( source.getUsername() );
switchEntity.setConfigurePort( source.getConfigurePort() );
switchEntity.setVtepVlan( source.getVtepVlan() );
switchEntity.setVtepIp( source.getVtepIp() );
switchEntity.setResourceName( source.getResourceName() );
switchEntity.setAccessPoint( source.getAccessPoint() );
switchEntity.setResourceType( source.getResourceType() );
switchEntity.setIsInitialized( source.getIsInitialized() );
switchEntity.setSysMac( source.getSysMac() );
return switchEntity;
}
}
可以看出pwd和password的映射关系符合我们定义的@Mapping.
4.3. 总结
以上是针对Mapstruct插件的基本介绍和基本的使用方式,在日常开发中使用Mapstruct可以大量减少不同层数据相互转换的代码。除了本文中举例的基础转换,mapstruct还支持开发者自定义很多更加复杂的映射规则,覆盖更多数据转换场景。
5. 参考
- https://mapstruct.org/documentation/stable/reference/html/#_custom_accessor_naming_strategy
- https://blog.csdn.net/qq_44732146/article/details/119968376