1

I have Class A, B and C. Class A has three variables and it gets populated based on different fields of Class B and C. When I use mapper to populate object only last used mapper values are retained. How can I make sure that all values are populated. I am using MapStruct mapper(version 1.2.0) with Spring Boot version 2.0.3

Sample code below:
Class A{

  String a;
  String b;
  String c;

  }

Class B{
 String b1;
}

Class C{
    String c1;
}

public interface AtoCmapper{
  @Mappings({
      @Mapping(target="c", source="source.c1")
  })
  A CtoA(C source);

  @Mappings({
      @Mapping(target="c1", source="source.c")
  })
  C AtoC(A source);
}

public interface AtoBmapper{
  @Mappings({
      @Mapping(target="b", source="source.b1")
  })
  A BtoA(B source);

  @Mappings({
      @Mapping(target="b1", source="source.b")
  })
  B AtoB(A source);
}

Class DAO{

 @Autowired
 AtoBmapper aToBMapper;

 @Autowired
 AtoCmapper aToCMapper;

 public void testMapping(){
  A aObject = new A();

  aObject = aToBMapper(bObject); // Assume bObject is object to Type B and it is initialized properly

  aObject = aToCMapper(cObject); // Assume cObject is object to Type B and it is initialized properly
 }

 //Now when I call testMapping() resulting A object only has value set for variable c, value of b is lost.
 How can I make sure that Values from B and C are set properly to Class A
}
user1575601
  • 397
  • 1
  • 7
  • 20

1 Answers1

3

MapStruct can update existing instances! To do this, introduce new mapping methods (or replace the old ones) by variants which have a second @MappingTarget annotated parameter of the type A (and in this case one may replace the return type by void):

// In AtoBmapper
@Mappings(...)
void updateAFromB(B source, @MappingTarget A target);

// In AtoCmapper
@Mappings(...)
void updateAFromC(C source, @MappingTarget A target);

Then you can write:

A aObject = new A();

aToBMapper.updateAFromB(bObject, aObject);
aToCMapper.updateAFromC(cObject, aObject);

// now aObject should contain the cumulated data from b and c
Hero Wanders
  • 3,237
  • 1
  • 10
  • 14