Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapstruct : Use of context in source argument of @Mapping

Tags:

mapstruct

When using multiple arguments in a @Mapper, it seems that the @Context arguments is unreachable

public interface MyMapper {  
      @Mapping(target="target1", source="arg1.arg") //works
      @Mapping(target="target2", source="arg2") //works
      @Mapping(target="target3", source="arg2.arg") //works
      @Mapping(target="target2", source="context.arg") //NOT WORKING
      public MyTarget convert(Object arg1, Object arg2, @Context Object context);
      
}

I am trying to use and expression="" to work around it, but I can't get it to work.

Any suggestions?

I can see I am not the only one to ever wish this. https://github.com/mapstruct/mapstruct/issues/1280

Thanks

like image 340
Filip Avatar asked Sep 14 '25 14:09

Filip


2 Answers

I ran into the same scenario as I needed a @Context param to be able to pass to a nested mapping function, but also wanted to use it as a source in a @Mapping. I was able to achieve this using expression as follows:

public interface MyMapper {

  @Mapping(target="target1", source="arg1")
  @Mapping(target="target2", source="arg2")
  @Mapping(target="target3", expression="java( contextArg )")
  public MyTarget convert(Object arg1, Object arg2, @Context Object contextArg);

}
like image 53
nalapoke Avatar answered Sep 17 '25 21:09

nalapoke


To answer your second question:


public interface MyMapper {

  @Mapping(target="target1", source="arg1.arg")
  @Mapping(target="target2", ignore = true ) // leave to after mapping 
  MyTarget convert(Object arg1, @Context Object context);

  @AfterMapping
  default void convert(Object arg1, @MappingTarget MyTarget target, @Context context) {
        target.setTarget2( convert (context) );
  } 

  // if you have multipe mappings, you could address them here
  @Mapping(target="target2", source="context.arg") 
  MyInnerTarget convert(Object arg1, Object context);
}

like image 35
Sjaak Avatar answered Sep 17 '25 19:09

Sjaak