tmeusburger
10/6/2017 - 12:44 AM

Mapstruct Example Question

Mapstruct Example Question

public class SourceObject {
    private String trackingNumber;

    public String getTrackingNumber() {
        return trackingNumber;
    }

    public void setTrackingNumber(String trackingNumber) {
        this.trackingNumber = trackingNumber;
    }
}

public class DestinationObject {
    private String trackingNumber;
    private List<ListObject> listObjects;

    public String getTrackingNumber() {
        return trackingNumber;
    }

    public void setTrackingNumber(String trackingNumber) {
        this.trackingNumber = trackingNumber;
    }

    public List<ListObject> getListObjects() {
        return listObjects;
    }

    public void setListObjects(List<ListObject> listObjects) {
        this.listObjects = listObjects;
    }
}

public class ListObject {
    private String trackingNumber;

    public String getTrackingNumber() {
        return trackingNumber;
    }

    public void setTrackingNumber(String trackingNumber) {
        this.trackingNumber = trackingNumber;
    }

}

@Mapper
public abstract class SourceObjectMapper {

    @Mapping(source = "trackingNumber", target = "trackingNumber")
    @Mapping(source = "?this?", target = "listObjects")
    abstract DestinationObject sourceObjectToDestinationObject(SourceObject sourceObject);

    public List<ListObject> sourceObjectToStringList(SourceObject sourceObject) {
        String trackingNumber = sourceObject.getTrackingNumber();
        ListObject listObject = new ListObject();
        listObject.setTrackingNumber(trackingNumber);
        return Arrays.asList(listObject);
    }
    
    // I'm looking for a way to have my resultant object looks like this
    // SourceObject.trackingNumber = "12345"
    /* DestinationObject -> 
          trackingNumber = "12345"
          List<ListObject> = [ListObject.trackingNumber = "12345"]          
    */
    
    // I'm not sure if the best way is to find a way to pass in the source object somehow via the mapping 
    //    or to find a way to turn a non-iterable object into a list of a single element
}