how to map collection to nested property

1,185 views
Skip to first unread message

Anton Dorn

unread,
Jun 1, 2015, 5:22:07 PM6/1/15
to mapstru...@googlegroups.com


public class SourceObj {

    private List<String> myStrings;


public class TargetObj {

    private InsideClass inside;


public class InsideClass {

private List<String> someStrings;


@Mapper
public interface MyMapper {
    @Mappings( {
        @Mapping( source = "myStrings", target = "inside.someStrings")
    } )
    TargetObj toTarget( SourceObj s );



Basically i need to map two Lists but they are at different level of hierarchy in Source and Target. I thought i can use bean expressions, but getting an error. Is there an easy way around this?

Sorry if this has obvious solution, i'm new to mapstruct (and i went through reference and IterableNonIterable sample as well)

Thanks,
Anton

Anton Dorn

unread,
Jun 1, 2015, 8:34:22 PM6/1/15
to mapstru...@googlegroups.com
i figured i can do it with abstract class, but wonder if there is more elegant way:

     @Mapping( source = "myStrings", target = "inside")
    } )
    abstract TargetObj toTarget( SourceObj s );
    
    abstract List<String> toStrings(List<String> strs);
    
    public InsideClass myStringsToInside(List<String> myStrings){
    InsideClass inside = new InsideClass();
   
    inside.setSomeStrings(MAPPER.toStrings(myStrings));
   
    return inside;

Gunnar Morling

unread,
Jun 2, 2015, 2:11:20 AM6/2/15
to mapstru...@googlegroups.com
Hi Anton,

Yes, your approach would be suggestion as well. Only you shouldn't need the toStrings() method, calling

    inside.setSomeStrings( new ArrayList<String> (myStrings) );

should suffice in myStringsToInside().

There is an issue in our tracker around supporting nested properties in target(), but there are still some problems around that to solve, so we are not sure yet whether to implement this or not.
--Gunnar

--
You received this message because you are subscribed to the Google Groups "mapstruct-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mapstruct-use...@googlegroups.com.
To post to this group, send email to mapstru...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages