如何使用MapStruct实现单元素List到TargetPhone的Java Bean映射?
使用MapStruct实现Java Bean映射(单元素List转单个对象)
核心需求
将Source类中始终仅含一个元素的List<Phone>映射为Target类中的TargetPhone对象,同时完成其他字段的名称映射。
步骤1:添加MapStruct依赖(Maven示例)
在pom.xml中引入MapStruct核心依赖与注解处理器:
<dependencies> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct</artifactId> <version>1.5.5.Final</version> <!-- 可替换为最新稳定版 --> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>11</source> <!-- 根据自身JDK版本调整 --> <target>11</target> <annotationProcessorPaths> <path> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>1.5.5.Final</version> </path> </annotationProcessorPaths> </configuration> </plugin> </plugins> </build>
步骤2:定义MapStruct映射接口
创建映射接口,通过自定义方法处理List<Phone>到TargetPhone的转换,并用@Mapping注解处理字段名称不一致的映射:
import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.Named; import java.util.List; @Mapper(componentModel = "spring") // 可选,根据依赖注入容器选择,如spring、cdi等 public interface SourceTargetMapper { // 主映射方法 @Mapping(source = "name", target = "myName") @Mapping(source = "age", target = "myAge") @Mapping(source = "phones", target = "targetPhone", qualifiedByName = "listToTargetPhone") Target sourceToTarget(Source source); // 自动生成Phone到TargetPhone的字段映射 @Mapping(source = "id", target = "myId") @Mapping(source = "phoneNumber", target = "myPhoneNumber") @Mapping(source = "phoneColor", target = "myPhoneColor") TargetPhone phoneToTargetPhone(Phone phone); // 自定义转换逻辑:从单元素List中取出Phone并转为TargetPhone @Named("listToTargetPhone") default TargetPhone listToTargetPhone(List<Phone> phones) { if (phones == null || phones.isEmpty()) { return null; // 可根据业务需求调整空列表处理逻辑 } return phoneToTargetPhone(phones.get(0)); } }
步骤3:使用映射接口
在业务代码中注入或实例化映射接口,调用转换方法完成映射:
// Spring环境下直接注入 @Autowired private SourceTargetMapper mapper; public void performConversion() { Source source = new Source(); source.setName("张三"); source.setAge(25); Phone phone = new Phone(); phone.setId(1L); phone.setPhoneNumber("13800138000"); phone.setPhoneColor("黑色"); source.setPhones(List.of(phone)); Target target = mapper.sourceToTarget(source); // 此时target的myName为"张三",myAge为25,targetPhone的字段已完成对应映射 }
内容的提问来源于stack exchange,提问作者user2034519
相关产品推荐
相关产品推荐

