Skip to content
Advertisement

Map several fields to List with a mapstruct

for example, I have following entity:

class Bank
{
String name;
String employee1;
String employee2;
}

And a Dto object:

class BankDto
{
String name;
List<String> employeeList;
}

Is there a proper way how to map Bank to BankDto, so employee1 and employee2 fields will be added to employeeList collection?

Advertisement

Answer

You can resolve your issue by adding an after mapping method to your mapping interface:

@Mapper
public abstract class Mapper {

    public abstract BankDto getBankDto(Bank bank);

    @AfterMapping
    public void setEmployees(Bank bank, @MappingTarget BankDto bankDto) {
        bankDto.setEmployeeList(new List<String>());
        bankDto.getEmployeeList().add(bank.employee1);
        bankDto.getEmployeeList().add(bank.employee2);
    }
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement