Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map nested collections using MapStruct?

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?

like image 408
gschambial Avatar asked Aug 22 '17 09:08

gschambial


People also ask

How do I map a MapStruct collection?

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.

What is @MappingTarget?

@Target(PARAMETER) @Retention(CLASS) public @interface 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 .

How do I set default value in MapStruct?

Syntax. default-value − target-property will be set as default-value in case source-property is null.


1 Answers

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);
}
like image 185
jannis Avatar answered Oct 02 '22 15:10

jannis