19

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?

2

2 Answers 2

6

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();
        }
    }
Sign up to request clarification or add additional context in comments.

1 Comment

abstract method of mapStringtoList is not necessary and you should add ChildSource childFromString(String child) implementation
3

Using a default method to map the ChildSource to a String.

@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);
    
    default String mapChildSourceToString(ChildSource child) {
        return child.getAction();
    }
}

1 Comment

Please edit your post to explain how it answers the question.

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.