Mapping List<String> from List<Object> using mapstruct

bhuvana picture bhuvana · Oct 6, 2017 · Viewed 9.1k times · Source

Hi I am getting null for List action in DTO while setting it from the Child Source class using mapstruct. Could some help me in resolving this. Please find my code here

Entity Class:

public class Source {
    int id;
    String name;
    List<ChildSource> childSource;
    //getters and setters
}

public class ChildSource {
    String code;
    String action;
    //getters and setters   
}

DestinationDTO:

public class TargetDTO{
    int sNo;
    String mName;
    List<String> actions;
    //getters and setters  
}

MApper Class:

@Mapper(componentModel = "spring")    
public abstract class SampleMapper {
        @Mappings({ 
            @Mapping(target = "id", source = "sno"),
            @Mapping(target = "name", source = "mNAme")
        })
        public abstract TargetDTO toDto(Source source);

        @IterableMapping(elementTargetType = String.class)
        protected abstract List<String> mapStringtoList(List<ChildSource> childSource);

        protected String mapChildSourceToString(ChildSource child) {
            return child.getAction();
        }
    }

But my action list is setting as null in the target dto. Could anyone help me here please?

Answer

kinath_ru picture kinath_ru · Aug 17, 2018

You can do it like this.


@Mapper(componentModel = "spring")    
public abstract class SampleMapper {
        @Mappings({ 
            @Mapping(target = "id", source = "sno"),
            @Mapping(target = "name", source = "mNAme"),
            @Mapping(target = "actions", source = "childSource")
        })
        public abstract TargetDTO toDto(Source source);

        protected abstract List mapStringtoList(List childSource);

        protected String mapChildSourceToString(ChildSource child) {
            return child.getAction();
        }
    }