Collections 集合中的mapstruct服务映射

Collections 集合中的mapstruct服务映射,collections,nested,mapping,mapstruct,Collections,Nested,Mapping,Mapstruct,我有一位家长,他有一组我想映射的孩子 Parent -> Collection<Child> children ParentDTO -> Collection<ChildDTO> childDTOs 现在在父DTotomain(parentDTO)中,我希望mapstruct对集合中的每个项进行查找 此解决方案适用于单个occ,mapstruct可以在服务中找到getChild并写入查找操作: @Mapper(uses = ChildService.clas

我有一位家长,他有一组我想映射的孩子

Parent -> Collection<Child> children
ParentDTO -> Collection<ChildDTO> childDTOs
现在在父DTotomain(parentDTO)中,我希望mapstruct对集合中的每个项进行查找

此解决方案适用于单个occ,mapstruct可以在服务中找到getChild并写入查找操作:

@Mapper(uses = ChildService.class)
public interface ParentMapper {

    @Mapping(source="child.id", target="child")
    Parent dtoToDomain(ParentDTO parentDTO);
}
但是,对于集合,我必须为集合映射指定一个特定的方法,但是我在@mapping中放了什么呢?像这样的

@Mapping(source="child.id", target="child")
Collection<Child> dtoToDomain(Collection<ChildDTO> children)

但目标在mapstruct中是必需的。也许我可以将整个对象指定为目标?

我想您正在寻找

使用
@ObjectFactory
可以基于源对象创建映射实例

比如说

public class ChildFactory {


    private final ChildService childService;

    public ChildFactory(ChildService childService) {
        this.childService = childService;
    }


    public Child createChild(ChildDto dto) {
        if (dto.getId() == null) {
            return new Child();
        } else {
            return childService.findById(dto.getId());
        }
    }
}
现在,您可以在
ChildMapper
中使用
ChildFactory
。将来可能会将工厂作为
@Context
传递。看

@Mapper(uses = ChildMapper.class)
public interface ParentMapper {

    Parent dtoToDomain(ParentDTO parentDTO);
}

@Mapper(uses = ChildService.class)
public interface ChildMapper {

    @Mapping(source="id", target="")
    Child dtoToDomain(ChildDTO child);
}
public class ChildFactory {


    private final ChildService childService;

    public ChildFactory(ChildService childService) {
        this.childService = childService;
    }


    public Child createChild(ChildDto dto) {
        if (dto.getId() == null) {
            return new Child();
        } else {
            return childService.findById(dto.getId());
        }
    }
}