MapStruct Java: 属性 列表

MapStruct Java: property to list

不久,我想将这段代码移到 mapstruct 映射器中:

List<Provincia> provincies = resultSetType.getResults().getResult().stream()
    .map(resultType -> ResultTypeToProvinciaMapper.INSTANCE.resultTypeToProvincia(resultType))
    .collect(Collectors.toList());

我想要:

List<Provincia> provinces = ResultTypeToProvinciaMapper.INSTANCE.getList(resultSet);

详情

我的来源class:

public class ResultSetType {

    protected SearchRequestType request;
    protected Results results;
    protected Long resultCount;
    protected Long totalCount;
    protected Long startIndex;
    protected Long pageSize;
    protected ResultSetType.Errors errors;

    // getters & setters

}

其中 Results 是:

public static class Results {

    protected List<ResultType> result;

    // geters & setters

}

ResultType

public class ResultType {

    protected String id;
    protected String description;

    // getters & setters

}

我的 Service class 正在从我的 Repository:

中获取一个 ResultSetType 对象
@Service
@RequiredArgsConstructor
public class ServeiTerritorialServiceImpl implements ServeiTerritorialService {

    private final ServeiTerritorialClientRepository serveiTerritorialClientRepository;

    /**
     * {@inheritDoc}
     */
    @Override
    public void getPaisos() {
        ResultSetType resultSetType = this.serveiTerritorialClientRepository.getOid("2.16.724.4.400");

        // here I need to map resultSetType to a List<Provincia>...
    }

}

我需要将 resultSetType 映射到 List<Provincia>

所以,我需要将 resultSetType.results.result 映射到 List<Provincia>

首先,我创建了一个 mapper 以便将 ResultType 映射到 Provincia:

@Mapper
public interface ResultTypeToProvinciaMapper {
    
    ResultTypeToProvinciaMapper INSTANCE = Mappers.getMapper(ResultTypeToProvinciaMapper.class);
    
    @Mapping(source = "id", target = "code")
    @Mapping(source = "description", target = "name")
    Provincia resultTypeToProvincia(ResultType resultType);

}

但是,我不太明白如何从 resultSetType.results.resultList<Provincia>

有什么想法吗?

使用 MapStruct,您可以定义不同可迭代对象之间的映射。但是,您可以在方法中将嵌套列表映射到顶级列表(如果它被包装,则可以)。

无论如何,我建议您执行以下操作:

@Mapper
public interface ResultTypeToProvinciaMapper {
    
    ResultTypeToProvinciaMapper INSTANCE = Mappers.getMapper(ResultTypeToProvinciaMapper.class);
    

    default List<Provincia> resultSetToListOfProvincia(ResultSetType resultSetType) {
        if (resultSetType == null) {
            return null;
        }

        Results results = resultSetType.getResults();

        if (results == null) {
            return null;
        }
        return resultTypesToProvincias(results.getResult());
    }


    List<Provincia> resultTypesToProvincias(List<ResultType> resultTypes);

    @Mapping(source = "id", target = "code")
    @Mapping(source = "description", target = "name")
    Provincia resultTypeToProvincia(ResultType resultType);

}