如何用MapStruct自动映射POJO嵌套字段并避免表达式转地址列表?
MapStruct 映射优化方案
问题1:自动映射到嵌套的customer字段
不用逐个声明字段的核心思路是给嵌套对象单独定义映射方法,让MapStruct自动复用它来填充目标字段。
在映射接口里新增一个CustomerSource到CustomerTarget的基础映射方法:
// 定义基础映射,字段名匹配时MapStruct会自动处理 CustomerTarget toCustomerTarget(CustomerSource source); // 主映射方法,无需手动写customer的字段映射 @Mapping(target = "addresses", expression = "java(Collections.singletonList(toAddress(customer)))") CustomerAddresses toTarget(CustomerSource customer);
因为CustomerSource的firstname、lastname和CustomerTarget的字段名完全一致,MapStruct会自动完成这两个字段的映射,不需要额外添加@Mapping注解。
问题2:无需表达式生成地址列表
可以通过自定义列表转换方法替代expression,让代码更符合MapStruct的规范:
- 先定义
CustomerSource到Address的基础映射:
Address toAddress(CustomerSource source);
- 新增一个默认方法,把单个地址转为列表:
default List<Address> toAddressList(CustomerSource source) { return Collections.singletonList(toAddress(source)); }
- 修改主映射方法,直接引用这个列表转换方法:
// 基础映射方法 CustomerTarget toCustomerTarget(CustomerSource source); Address toAddress(CustomerSource source); // 主映射,用自定义方法生成地址列表 @Mapping(target = "addresses", source = ".") CustomerAddresses toTarget(CustomerSource customer); // 列表转换的默认方法 default List<Address> toAddressList(CustomerSource source) { return Collections.singletonList(toAddress(source)); }
MapStruct会自动识别返回值为List<Address>、参数为CustomerSource的方法,直接调用它来生成addresses字段,完全不需要写expression。
内容的提问来源于stack exchange,提问作者Bohdan Zv
相关产品推荐
相关产品推荐

