如何使用Map<String, Product>作为源映射为QuantityDTO对象?
解决Map<String, Product>到QuantityDTO的MapStruct映射问题
当源数据是Map<String, Product>类型时,你原有的写法无法生效,因为MapStruct不能直接解析"shoes.quantity"这类嵌套路径。以下是两种可行的解决方式:
方案一:使用@Mapping的expression属性
通过Java表达式明确调用Map的get()方法获取对应Product对象,再提取其quantity属性:
@Mapper public interface QuantityMapper { QuantityMapper INSTANCE = Mappers.getMapper(QuantityMapper.class); @Mapping(target = "shoes", expression = "java(map.get(\"shoes\").getQuantity())") @Mapping(target = "pants", expression = "java(map.get(\"pants\").getQuantity())") QuantityDTO mapToQuantityDto(Map<String, Product> map); }
如果需要避免空指针异常(比如Map为null、指定key不存在或Product对象为null),可以在表达式中增加空值判断:
@Mapping(target = "shoes", expression = "java(map != null && map.get(\"shoes\") != null ? map.get(\"shoes\").getQuantity() : null)") @Mapping(target = "pants", expression = "java(map != null && map.get(\"pants\") != null ? map.get(\"pants\").getQuantity() : null)")
方案二:自定义默认映射方法
在Mapper接口中编写默认方法,手动实现映射逻辑,这种方式更灵活,便于处理各种边界场景:
@Mapper public interface QuantityMapper { QuantityMapper INSTANCE = Mappers.getMapper(QuantityMapper.class); default QuantityDTO mapToQuantityDto(Map<String, Product> map) { if (map == null) { return null; } QuantityDTO dto = new QuantityDTO(); Product shoesProduct = map.get("shoes"); dto.setShoes(shoesProduct != null ? shoesProduct.getQuantity() : null); Product pantsProduct = map.get("pants"); dto.setPants(pantsProduct != null ? pantsProduct.getQuantity() : null); return dto; } }
注意事项
- 确保
Product类存在getQuantity()方法,MapStruct依赖Getter方法访问对象属性; - 根据业务场景决定是否添加空值判断,避免运行时出现空指针异常。
内容的提问来源于stack exchange,提问作者foubou
相关产品推荐
相关产品推荐

