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?
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.
@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 .
Syntax. default-value − target-property will be set as default-value in case source-property is null.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With