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
(数字格式化)
作用:格式化数字类型元素(如
BigDecimal
、Integer
)。示例:
[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);