Java 使用ModelMapper展平到ID列表

Java 使用ModelMapper展平到ID列表,java,modelmapper,Java,Modelmapper,我试图使用ModelMapper将子对象的集合映射到id号的列表 public class Child { private int id; private String childName; } public class Parent { private Set<Child> children; private String parentName; } public class ParentDto { private int[] child

我试图使用
ModelMapper
将子对象的
集合
映射到id号的
列表

public class Child {
    private int id;
    private String childName;
}

public class Parent {
    private Set<Child> children;
    private String parentName;
}

public class ParentDto {
    private int[] children; // Or use ArrayList<Integer>
    private String parentName;
}
setChildren
调用似乎需要是
map().add()
,但这也不起作用


欢迎您提出意见。

一种方法是创建一个
int[]
转换器,并使用它将
父.子项
映射到
父.子项

ModelMapper-mapper=newmodelmapper();
转换器子集到阵列转换器=
ctx->ctx.getSource()
.stream()
.mapToInt(子::getId)
.toArray();
createTypeMap(Parent.class,ParentDto.class)
.addMappings(映射->映射
.使用(ChildSetToInArrayConverter)
.地图(
父::getChildren,
ParentDto::setChildren
)
);
以下是完整的演示(使用和):

导入lombok.allargsconstuctor;
导入龙目数据;
导入org.modelmapper.Converter;
导入org.modelmapper.modelmapper;
导入java.util.Set;
公共班机{
公共静态void main(字符串[]args){
父项=新父项();
父项。setParentName(“父项”);
parent.setChildren(Set.of(
新生儿(1,“A”),
新生儿(2,“B”),
新生儿(3,“C”)
));
ModelMapper mapper=新的ModelMapper();
转换器子集到阵列转换器=
ctx->ctx.getSource()
.stream()
.mapToInt(子::getId)
.toArray();
createTypeMap(Parent.class,ParentDto.class)
.addMappings(映射->映射
.使用(ChildSetToInArrayConverter)
.地图(
父::getChildren,
ParentDto::setChildren
)
);
ParentDto dto=mapper.map(parent,ParentDto.class);
System.out.println(父级);
系统输出打印项次(dto);
}
@资料
@AllArgsConstructor
公共静态类子类{
私有int-id;
私有字符串childName;
}
@资料
公共静态类父类{
私人儿童;
私有字符串父名称;
}
@资料
公共静态类ParentDto{
私人儿童;
私有字符串父名称;
}
}
输出

Main.Parent(children=[Main.Child(id=3,childName=C),Main.Child(id=2,childName=B),Main.Child(id=1,childName=A)],parentName=Parent)
Main.ParentDto(children=[3,2,1],parentName=Parent)
    modelMapper.addMappings(new PropertyMap<Parent, ParentDto>() {
        @Override
        protected void configure() {
            using(ctx -> ctx.getSource().stream().map(Parent::getId).collect(Collectors.toList())
                .map().setChildren(source.getId()));
        };
    });


    Type listType = new TypeToken<ArrayList<ParentDto>>() {}.getType();
    ArrayList<ParentDto> parentDtos = new ArrayList<>();
    parentDtos = modelMapper.map(parents, listType);