0

I am trying to use MapStruct for a structure similar to the following:

@Data
public class ClassAEntity {
  private int id;
  private String name;
  private String numT;
  private List<ClassBEntity) bs;
}

@Data
public class ClassBEntity {
  private int id;
  private String name;
  private String numT;
  private List<Other> oc;
}

@Data
public class ClassA {
  private int id;
  private String name;
  private List<ClassB) bs;
}

@Data
public class ClassB {
  private int id;
  private String name;
  private List<Other> oc;
}

In the interface I have added the following mapping:

ClassAEntity map(ClassA classA, String numT)

I get a warning because it can't map numT to classBEntity.numT and I can't add it with @Mapping in the following way:

@Mapping(source = "numT", target = "bs[].numT")

On the other hand I need to ignore the parameter oc of classBEntity because "Other" object contains classAEntity and forms a cyclic object. (because I use oneToMany JPA). I have tried the following:

@Mapping(target = "bs[].oc", ignore = true)

Thank you for your help

1 Answer 1

2

MapStruct does not support defining nested mappings for collections. You will have to define more explicit methods.

For example to map numT into bs[].numT and ignore bs[].oc you'll need to do something like:

@Mapper
public MyMapper {

    default ClassAEntity map(ClassA classA, String numT) {
        return map(classA, numT, numT);
    }
    
    ClassAEntity map(ClassA classA, String numT, @Context String numT);

    @AfterMapping
    default void setNumTOnClassBEntity(@MappingTarget ClassBEntity classB, @Context String numT) {
        classB.setNumT(numT);
    }

    @Mapping(target = "oc", ignore = "true")
    ClassBEntity map(ClassB classB);

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.