映射扁平的父/子列表

问题描述 投票:0回答:1

我有一个扁平的父/子对象,如下所示:

class Flattened {
  int parentId;
  int childId;
  int someParentProperty1, someParentProperty2, ...;
  int someChildProperty1, someChildProperty2, ...;
}

并且我正在尝试将

Flattened
对象列表映射到父/子的规范化嵌套列表,如下所示:

class Parent {
  int parentId;
  int someParentProperty1, ...;
  List<Child> children;
}

class Child {
  int childId;
  int someChildProperty1, ...;
}

List<Parent> map(List<Flattened> flattenedList);

将父字段从

Flattened
对象映射到
Parent
很容易,更棘手的一点是将
Child
列表中的所有
Flattened
对象累积到每个
Parent.children
字段中。有没有一种优雅的方法可以使用 Mapstruct 来做到这一点?

mapstruct
1个回答
0
投票

我认为不可能将所有逻辑委托给 MapStruct,但可以肯定的是您可以依赖它来进行映射。

我不知道有比这更好的解决方案:

@Mapper(componentModel = MappingConstants.ComponentModel.SPRING, injectionStrategy = InjectionStrategy.CONSTRUCTOR)
public interface MyMapper {

    MyMapper INSTANCE = Mappers.getMapper(MyMapper.class);

    default List<Parent> map(List<Flattened> flattenedList) {
        Map<String, List<Flattened>> groupedFlattened = flattenedList.stream()
                .collect(Collectors.groupingBy(Flattened::getParentId));

        return groupedFlattened.entrySet().stream().map(entry -> {
            List<Flattened> flattenedChildren = entry.getValue();
            return mapFlattenedToParent(flattenedChildren.get(0), flattenedChildren);
        }).collect(Collectors.toList());
    }

    @Named("mapFlattenedToParent")
    @Mapping(target = "children", source = "flattenedChildren", qualifiedByName = "mapFlattenedToChild")
    Parent mapFlattenedToParent(Flattened flattened, List<Flattened> flattenedChildren);

    @IterableMapping(qualifiedByName = "mapFlattenedToChild")
    List<Child> mapFlattenedToChildren(List<Flattened> flattenedList);

    @Named("mapFlattenedToChild")
    Child mapFlattenedToChild(Flattened flattened);

}

您可以在我的 GitHub 上找到一个测试用例:MappingAFlattenedParentChildListTest.java

© www.soinside.com 2019 - 2024. All rights reserved.