mapping 2 objects over to collection

1,210 views
Skip to first unread message

Anton Dorn

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

I've got the following source:

class Source{

     ClassA propA;
    ClassB propB;

}

class Target{
   List<ClassAB> list;
}

I'm trying to create 2 elements of ClassAB in list and map propA to 1st, propB to 2nd.

i tried:

public abstract ClassAB map1(ClassA value);
public abstract ClassAB map2(ClassB value);
    void map1(ClassB prevValue, @MappingTarget List<ClassAB> list){
    ClassAB type = map2(prevValue);
    list.add(type);
    }

    void map2(ClassA value, @MappingTarget List<ClassAB> addresses){
     ClassAB type = map2(prevValue);
     list.add(type);
    }

Getting errors when generating. I believe i've see somewhere that i can map multiple sources to one target but i can't find it in reference... 

Thanks in advance for any suggestions :)
Anton

Gunnar Morling

unread,
Jun 2, 2015, 12:45:09 PM6/2/15
to Anton Dorn, mapstru...@googlegroups.com
Hi Anton,

You can indeed combine several sources to one target object (see http://mapstruct.org/documentation/#section-def-mapper-03), but that's a bit different from what you are trying to do.

Using a Java expression (see http://mapstruct.org/documentation/#section-expressions) may do the trick, assuming you have (generated or manually written methods for mapping ClassA/ClassB to ClassAB):

    @Mapping(target="list", expression="java( Arrays.asList( toClassAb( source.getPropA() ), toClassAb( source.getPropB() ) )")
    public Target sourceToTarget(Source source);

Out of interest, what's your actual use case for this? Combining two distinct source props into one target list is something I've not come across before :)

Hth,

--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.

Anton Dorn

unread,
Jun 2, 2015, 2:28:35 PM6/2/15
to mapstru...@googlegroups.com, agr...@gmail.com
Thanks!!! I ended up using ListUtils from apache-collections. 

Well, i'm transforming pretty flat structure into xml schema where a lot of elements are presented as lists (with type on each element saying what it is, eg. Home/Work for address). 
And in source objects, i've got separate elements for homeaddress and workaddress.
Reply all
Reply to author
Forward
0 new messages