Search code examples
javamapstruct

Map source class to a target field


I'm working on spring boot application where, I have two classes namely A and B.

@Data
class A{
 int id;
 String name;
}
@Data
class B{
 int bId;
 A a;
}

I need to map a field of class B which is a using mapstruct. How to map a source class A to target field a as well as to class B. Example mapper will be like

@Mapping(source="id", target="bId")
B fromClassA(A a);

Solution

  • You can use @AfterMapping, something like this:

    @Mapping(source="id", target="bId")
    B fromClassA(A a);
    @AfterMapping
    default void fillAinB(@MappingTarget B target, A source) {
      b.setA(source);
    }