java 如何使用 MapStruct 映射嵌套集合?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45814147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:55:11  来源:igfitidea点击:

How to map nested collections using MapStruct?

javacollectionsmapstruct

提问by gschambial

I have 2 entities:

我有 2 个实体:

Entity 1:

实体 1:

public class Master {

    private int id;
    private Set<SubMaster> subMasters= new HashSet<SubMaster>(0);
}

public class SubMaster{
    private int subId;
    private String subName;
}

Entity 2:

实体 2:

public class MasterDTO {

    private int id;
    private Set<SubMaster> subMasters= new HashSet<SubMaster>(0);
}

public class SubMasterDTO{
    private int subId;
    private String subName;
}

I am using MapStruct Mapper to map values of POJO to another.

我正在使用 MapStruct Mapper 将 POJO 的值映射到另一个。

public interface MasterMapper{
    MasterDTO toDto(Master entity);
}

I am able to successfully map Masterto MasterDTO. But, the nested collection of SubMasterin Masteris not getting mapped to its counterpart in MasterDTO.

我能够成功映射MasterMasterDTO. 但是,SubMasterin的嵌套集合Master没有映射到MasterDTO.

Could anyone help me in right direction?

任何人都可以帮助我朝着正确的方向前进吗?

回答by jannis

This examplein Mapstruct's Github repo is an exact showcase for what you're trying to do.

Mapstruct 的 Github 存储库中的这个示例准确展示了您要执行的操作。

TL;DR You'll need a separate mapper for the SubMaster(let's call it SubMasterMapper) class and then put a @Mapper(uses = { SubMasterMapper.class })annotation on your MasterMapper:

TL;DR 您将需要一个单独的映射器用于SubMaster(我们称之为SubMasterMapper)类,然后@Mapper(uses = { SubMasterMapper.class })在您的类上添加注释MasterMapper

public interface SubMasterMapper {
    SubMasterDTO toDto(SubMaster entity);
}

@Mapper(uses = { SubMasterMapper.class })
public interface MasterMapper {
    MasterDTO toDto(Master entity);
}