A1t0r
A1t0r

Reputation: 489

MapStruct: mapping from object with a list of complex object

Supposing I have the following classes:

public class A {
private String id;
private List<B> related;
}

public class B {
private String id;
private String name;
}

public class ADTO {
private String id;
private List<BDTO> relations;
}

public class BDTO {
private String identificator;
private String relatedName;
}

How can I create a mapper that given an A object type returns me an ADTO object with all the information? I have to create two different mappers? Can it be done in only one mapper? I think it would be something like the following, but I don't know how to map the atributtes from the list:

@Mapper
public interface MyMapper {

    @Mappings({ @Mapping(source = "related", target = "relations") })
    ADTO mapperA(A obj);
}

Thanks in advance.

Upvotes: 2

Views: 2248

Answers (1)

Panos K
Panos K

Reputation: 1091

try this (not tested but should work properly)

when you mapping lists you should make a map for both the class element and the list to map all the elements of the list)

@Mapper
public interface MyMapper {

    @Mappings({ @Mapping(source = "related", target = "relations") })
    ADTO mapperA(A obj);

    @Mappings(
      { @Mapping(source = "id", target = "identificator") },
      { @Mapping(source = "name", target = "relatedName") })
    BDTO bDTOMapping(B b);

    List<BDTO> bDTOListMapping(List<B> bList);
}

Upvotes: 3

Related Questions