-1

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);
chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
vinter
  • 466
  • 1
  • 3
  • 13

2 Answers2

1

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);
}
Grigorii Riabov
  • 185
  • 2
  • 8
1

The best way to do the mapping would be to define it in @Mapping.

e.g.

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

You can use the name of the parameter in the Mapping#source

Filip
  • 19,269
  • 7
  • 51
  • 60