当前位置: 首页 > news >正文

MapStruct注解完全手册:@Mapping参数详解与实战指南

引入依赖

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

新建一个抽象类或者接口

@Mapper(builder = @Builder(disableBuilder = true))
public interface AccountCopier {/*** 对象拷贝接口实例*/AccountCopier INSTANCE = Mappers.getMapper(AccountCopier.class);
}

@Mapper映射规则

默认映射规则
同类型日同名的属性,会自动映射

 mapstruct会自动进行类型转换
1.8种基本类型和他们对应的包装类型之间

2.8种基本类型(包括他们的包装类型)和string之间
3.日期类型和string之间 

@Mapping和@Mappings 

指定属性之间的映射关系
日期格式化:dateFormat="yyyy-MM-dd HH:mm:ss'。

数字格式化:numberFormat="#.00”

ignore
属性是引用对象的映射处理

参数整理

参数名称功能描述使用示例
target指定目标属性名(支持嵌套路径)@Mapping(target = "userName")
source指定源属性路径(支持点操作符)@Mapping(source = "user.name")
dateFormat日期格式化(遵循SimpleDateFormat)dateFormat = "yyyy-MM-dd"
numberFormat数字格式化(遵循DecimalFormat)numberFormat = "$#.00"
constant设置固定常量值constant = "ACTIVE"
defaultValue空值默认值(自动类型转换)defaultValue = "N/A"
expression使用Java表达式计算值expression = "java(null)"
ignore忽略映射该目标属性ignore = true
qualifiedByName指定自定义转换方法(配合@Named)qualifiedByName = "formatName"

@Named

为自定义映射方法提供唯一标识名称,不是必须的

应用目标示例代码使用场景
Mapper 接口方法@Named("dateToStr")
String dateToString(Date date)
定义可复用的转换逻辑
Mapper 抽象类方法@Named("trimSpaces")
default String trim(String str) { ... }
实现默认转换逻辑
外部工具类方法@Named("encrypt")
public static String encryptData(String data)
复用外部工具类中的转换方法

 举例:

@Mapper
public interface ProductMapper {@Named("toUpperCase")String upperCase(String str) { return str.toUpperCase(); }@Named("toLowerCase")String lowerCase(String str) { return str.toLowerCase(); }// 明确指定使用大写转换@Mapping(target="name", source="rawName", qualifiedByName = "toUpperCase")ProductDto toDto(Product product);
}

@MappingTarget

作为映射的目标对象,而不是创建一个对象。也就是target和source都存在的情况下

 /*** 更新简历信息** @param model  简历模型* @param resume 简历信息*/void update(@MappingTarget VitaeModel model, Resume resume);
import org.mapstruct.factory.Mappers;public class Main {public static void main(String[] args) {// 1. 创建一个 ImprovePositionParam 对象 (源对象)ImprovePositionParam param = new ImprovePositionParam();param.setPositionName("New Position Name");param.setDescription("New Description");// 2. 创建一个已经存在的 Position 对象 (目标对象)Position position = new Position();position.setId(123L);position.setPositionName("Old Position Name");position.setDescription("Old Description");// 3. 获取 PositionMapper 实例PositionMapper positionMapper = Mappers.getMapper(PositionMapper.class);// 4. 执行映射positionMapper.copying(param, position);// 5. 打印结果System.out.println("Position ID: " + position.getId());System.out.println("Position Name: " + position.getPositionName());System.out.println("Position Description: " + position.getDescription());}
}

输出:

Position ID: 123
Position Name: New Position Name
Position Description: New Description

List转List

@IterableMapping 

处理 集合元素映射 的核心注解

关键属性及用法

  1. dateFormat(日期格式化)

作用:将集合中的 Date 元素格式化为指定格式的字符串。

示例[Date("2023-10-01")] → ["2023-10-01"]

@IterableMapping(dateFormat = "yyyy-MM-dd")
List<String> datesToFormattedStrings(List<Date> dates);

2. numberFormat(数字格式化)

作用:格式化数字类型元素(如 BigDecimalInteger)。

示例[10.5] → ["$10.50"]

@IterableMapping(numberFormat = "$#.00")
List<String> formatPrices(List<BigDecimal> prices);

 3. qualifiedByName(自定义映射方法)常用!!!

作用:对集合中的每个元素应用自定义转换逻辑。

示例["a", "b"] → ["A", "B"]

// 定义自定义映射方法
@Named("toUpperCase")
String toUpperCase(String source) {return source.toUpperCase();
}// 在集合映射中引用
@IterableMapping(qualifiedByName = "toUpperCase")
List<String> mapToUppercaseList(List<String> sourceList);

 示例

 
    /*** 对象信息拷贝** @param entity 对象信息* @return dto信息*/@Named("qiJingAccount2dto")@Mapping(target = "code", source = "wxid")InactiveAccountDTO copying(QijingAccount entity);/*** 对象信息拷贝** @param entity 对象信息* @return dto信息*/@IterableMapping(qualifiedByName = "qiJingAccount2dto")List<InactiveAccountDTO> copyings(Collection<QijingAccount> entity);

相关文章:

  • 网络测试实战:金融数据传输的生死时速
  • 【Go】3、Go语言进阶与依赖管理
  • 软件上线前为什么要做性能测试?
  • QT开发技术【ffmpeg + QAudioOutput】音乐播放器 完善
  • 使用 HTML +JavaScript 从零构建视频帧提取器
  • 【.net core】天地图坐标转换为高德地图坐标(WGS84 坐标转 GCJ02 坐标)
  • 电脑提示dll文件缺失怎么办 dll修复方法
  • 用电脑控制keysight示波器
  • 《一生一芯》数字实验三:加法器与ALU
  • ASP.NET Core使用Quartz部署到IIS资源自动被回收解决方案
  • Ubuntu崩溃修复方案
  • 购物商城网站 Java+Vue.js+SpringBoot,包括商家管理、商品分类管理、商品管理、在线客服管理、购物订单模块
  • 船舶事故海上搜救VR情景演练全场景 “复刻”,沉浸式救援体验​
  • 机器学习的数学基础:决策树
  • Unity VR/MR开发-VR设备与适用场景分析
  • HTML中各种标签的作用
  • 为什么要选择VR看房?VR看房有什么优点?
  • html - <mark>标签
  • 【Go语言基础【3】】变量、常量、值类型与引用类型
  • html文字红色粗体,闪烁渐变动画效果,中英文切换版本
  • 江苏优化网站/江苏网站推广公司
  • 广州网站建设网站/外包公司有哪些
  • 电脑上如何进入wordpress/优化seo哪家好
  • 商家免费入驻平台/网站建设及推广优化
  • 电子商务网站建设和管理的意义/深圳seo推广
  • 哪个公司做外贸网站好/网络营销的手段包括