How to map nested collections using MapStruct?

蓝咒 提交于 2020-01-02 03:00:54

问题


I have 2 entities:

Entity 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:

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.

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

I am able to successfully map Master to MasterDTO. But, the nested collection of SubMaster in Master is not getting mapped to its counterpart in MasterDTO.

Could anyone help me in right direction?


回答1:


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

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:

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

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


来源:https://stackoverflow.com/questions/45814147/how-to-map-nested-collections-using-mapstruct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!