1

I have a CXF generated class which has a collection as its only property. I need to map a single value from my DTO into an element of that collection, as in:

class DTO {
    String dto;
}

class A {
    String a;
}

class B {
    List<A> b;
}

interface Mapper {
    @Mappings({
        @Mapping(source="dto", target="b.a")
    })
    B getBfromDTO(DTO dto);
}

Should this really work? If so, how could I configure this mapping?

lpacheco
  • 976
  • 1
  • 14
  • 27
  • Possible duplicate of [MapStruct String to List mapping](http://stackoverflow.com/questions/37143179/mapstruct-string-to-list-mapping) – Wolfie Apr 06 '17 at 18:55

1 Answers1

1

I couldn't find out a way to do this as a mapping, and from other answers from @Gunnar I now understand this is not possible, but I found a workaround using the annotation @AfterMapping.

@AfterMapping allow to specify methods to be run after a mapping occurs, so I created mappings for the non-collection properties of my objects and an @AfterMapping for filling collections in the objects.

class DTO {
    String a;
    String x;
}

class A {
    String a;
}

class B {
    String x;
    List<A> b;
}

abstract class Mapper {
    @Mappings({
        @Mapping(source="x", target="x")
    })
    protected abstract B getBfromDTO(DTO dto);

    @AfterMapping
    protected void fillCollections(DTO dto, @MappingTarget B b) {
        b.getB().add(dto.a);
    }
}
lpacheco
  • 976
  • 1
  • 14
  • 27