如何使用MapStruct将List<Long>转换为填充interfaceId的List<MenuInterfaceRelation>
实现方案
MapStruct 处理集合类型转换时,会自动扫描并复用对应单个元素的转换方法迭代执行,因此不需要直接在集合转换方法上加
@Mapping注解,核心是先定义Long类型转MenuInterfaceRelation单个对象的逻辑。
方案1:注解式单元素转换(无手动实现代码)
该写法最符合MapStruct规范,所有转换逻辑由MapStruct自动生成:
import org.mapstruct.Mapper; import org.mapstruct.Mapping; import java.util.List; // 不需要Spring托管可以删除componentModel属性 @Mapper(componentModel = "spring") public interface MenuInterfaceRelationMapper { // 单个Long转单个实体:单参数场景下source直接填入参名即可 @Mapping(target = "interfaceId", source = "interfaceId") MenuInterfaceRelation longToRelation(Long interfaceId); // 集合转换方法无需额外配置,MapStruct自动迭代调用上面的单元素转换方法 List<MenuInterfaceRelation> convertToRelationList(List<Long> interfaceIdList); }
方案2:自定义单元素转换逻辑(适合有复杂默认值赋值场景)
如果MenuInterfaceRelation的其他字段需要设置默认值,可以用default方法实现单元素转换:
import org.mapstruct.Mapper; import java.util.List; @Mapper(componentModel = "spring") public interface MenuInterfaceRelationMapper { // 自定义单元素转换逻辑,可灵活设置其他字段的默认值 default MenuInterfaceRelation longToRelation(Long interfaceId) { MenuInterfaceRelation relation = new MenuInterfaceRelation(); relation.setInterfaceId(interfaceId); // 示例:给otherId设置默认值0 relation.setOtherId(0L); return relation; } List<MenuInterfaceRelation> convertToRelationList(List<Long> interfaceIdList); }
不推荐的写法
不建议直接在集合方法上用表达式实现,可读性和可维护性较差:
// 可运行但不符合规范 @Mapping(target = "interfaceId", expression = "java(interfaceId)") List<MenuInterfaceRelation> convertToRelationList(List<Long> interfaceIdList);
内容的提问来源于stack exchange,提问作者xuweijsnj
相关产品推荐
相关产品推荐

