Mapstruct with two different sources

51 Views Asked by At

I'm trying to do the mapping between source and target.

@Data
@Builder
@Getter
public class Source {
    public String str3;
}

@Data
@Builder
@Getter
public class Target {
  public String str1;
  public String str2;
  public AnotherObj anotherObj;
}

@Data
@Builder
@Getter
public class AnotherObj {
  public String str3;
  public String str4;
}

I have a mapper like this

@Mapping(target = "anotherObj", source = "request", qualifiedByName = "mapAnotherObjToSource")
@Mapping(target = "anotherObj.str4", source = "str4")
Target convert(Source request, String str4);

But when I do this, I get an error like this: Java: No read accessor found for property anotherObj in target type.

I have my getter, what could be missing?

I tried using @AfterMapping like this

@AfterMapping
default void handleStr4(@MappingTarget Target target, Source source, String str4) {
if (target.getAnotherObj() != null) {
    target.getCardMetadataInfo().setStr4(str4);
    }
}
2

There are 2 best solutions below

2
Satyajit Bhatt On
// Set str4 value into handleStr4 method
@AfterMapping
default void handleStr4(Source source, @MappingTarget Target target, 
   String str4) {
       if (target.getAnotherObj() != null) {
           target.getAnotherObj().setStr4(str4);
   }
}
0
thunderhook On

This is not a problem with Lombok, but with the builder pattern in combinations like this.

You have several options:

  • Do not use nesting in the target and provide an intermediate method
  • Tell MapStruct not to use the lombok builder in this mapper with @Mapper(builder = @org.mapstruct.Builder(disableBuilder = true))

For more information on why this problem occurs, and an example with an intermediate method, see this comment in the MapStruct GitHub issue.