Search code examples
javamapstruct

mapstruct - iterable to noniterable within complex object context


I am currently facing mapstruct and it's beginner issues and one of them is the following.

I do know the samples proposal: https://github.com/mapstruct/mapstruct-examples/tree/master/mapstruct-iterable-to-non-iterable

And i do know generally to handles complex mappings, BUT i really got a blockade in my head mapping something like:

    @Mapping(target = "employee.mainAddress.address", source = "employee.registeredAddresses[0].privateAddresses[0].address")
    abstract EmployeeDto map(Employee employee);

Hope that the object structure is clear. in the source there are two lists and for each the first element should be chosen. How can this be done by mapstruct?


Solution

  • Just specify a Mapping method yourself. MapStruct can take the burden of most of your mapping code, but for some, you just need to help out a little. That's what the example tries to demonstrate.

    @Mapper
    public abstract class MyMapper{
    
        @Mapping(target = "employee.mainAddress.address", source = "employee.registeredAddresses")
        abstract EmployeeDto map(Employee employee);
     
        // implement a concrete method yourself that MapStruct can recognise and call in its generated code
        AddressDto map(List<PrivateAddress> source) {
    
         // perhaps do some NPE checking, call MapStruct generated method below
         return map( source.get(0).get(0) );
      }
    
      // continue letting MapStruct do the bulk of the work
      abstract AddressDto map(Address source);
    
    }