R111
R111

Reputation: 171

Mapping nested collection attribute with MapStruct 1.2.0

I'm trying to map the following attributes with MapStruct 1.2.0, based on the following Classes

ClassA {
String id
List <Object1> artefacts
}

DTOClassA{
String id
List <Object2> artefacts
}

Object1 {
String id
String serialNo
}

Object2 {
String id
String serialNo
}

Within my interface mapper, how do I map the serialNo from ClassA artefacts list to the serialNo DTOClassA artefacts list? I have tried the following but I didnt work:

@Mapping(target="artefacts.serialNo", source="artefacts.serialNo")
ClassA mapToDto(DTOClassA dto)

any help appreciated

Upvotes: 0

Views: 104

Answers (1)

Tilo Schulz
Tilo Schulz

Reputation: 36

using MapStruct v1.3.0 and having just the following Mapper set up

@Mapper
public interface TestSOMapper {
    ClassA mapToDto(DTOClassA dto);
}

leads to the following MapperImpl being auto-generated

...
protected Object1 object2ToObject1(Object2 object2) {
    if ( object2 == null ) {
        return null;
    }

    Object1 object1 = new Object1();

    object1.setId( object2.getId() );
    object1.setSerialNo( object2.getSerialNo() );

    return object1;
}
...

This is what you wanted, isn't it? If the names of the properties wouldn't match I'd suggest writing a second Mapper for Object1 > Object2 mapping.

I hope this helps!

Upvotes: 1

Related Questions