使用mapstruct<String>从List<Object>映射List

问题描述 投票:0回答:2

您好,我在使用 Mapstruct 从子源类设置 DTO 中的列表操作时得到 null。有人可以帮助我解决这个问题吗?请在这里找到我的代码

实体类:

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

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

目的地DTO:

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

映射器类:

@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();
        }
    }

但是我的操作列表在目标 dto 中设置为 null。有人可以帮我吗?

java dto mapstruct
2个回答
6
投票

你可以这样做。


@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();
        }
    }

2
投票

使用默认方法将 ChildSource 映射到字符串。

@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();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.