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?
Using Mapstruct we can map list in similar fashion as we map primitives. To get a list of objects, we should provide a mapper method which can map an object.
In general, mapping collections with MapStruct works in the same way as for simple types. Basically, we have to create a simple interface or abstract class and declare the mapping methods. Based on our declarations, MapStruct will generate the mapping code automatically.
Annotation Type MappingTarget Declares a parameter of a mapping method to be the target of the mapping. Not more than one parameter can be declared as MappingTarget . NOTE: The parameter passed as a mapping target must not be null .
@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();
}
}
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With