Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Orika - mapping object to list (one to many mapping)

Tags:

java

orika

I have following two classes

class A {
    class InnerA {
        private String field;

        // getters/setters
    }

    private Collection<InnerA> collection;

    // getters/setters
}

class B {
    private String field;

    // getters/setters
}

Is it possible to map A into Collection of B (A.collection.field should be mapped into Collection of B.field)?

I tried to use custom converter but I have only to manage java.lang.VerifyError:

    mapperFactory.getConverterFactory().registerConverter(new CustomConverter<A, Collection<B>>() {

        @Override
        public Collection<B> convert(
                A arg0, Type<? extends Collection<B>> arg1) {

            Collection<B> result = new ArrayList<B>();

            Iterator<Item> it = arg0.getCollection().iterator();
            while(it.hasNext()){
                it.next();
                result.add(new B());
            }

            return result;
        }

    });

results in:

java.lang.VerifyError: Inconsistent args count operand in invokeinterface in method    ma.glasnost.orika.generated.Orika_ArrayList_A_Mapper845657274.mapAtoB(Ljava/lang/Object;Ljava/lang/Object;Lma/glasnost/orika/MappingContext;)V at offset 74  
at java.lang.Class.getDeclaredConstructors0(Native Method)  
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2404)  
at java.lang.Class.getConstructor0(Class.java:2714)     
at java.lang.Class.newInstance0(Class.java:343)     
at java.lang.Class.newInstance(Class.java:325)  
like image 967
lbednaszynski Avatar asked Mar 12 '13 18:03

lbednaszynski


1 Answers

Of course you can map it, you have to just make InnerA public:

List<B> dest = mapper.mapAsList(sourceA.getCollection(), B.class);

If InnerA is not public, it can not be used by Orika

MapperFacade mapper = new ConfigurableMapper() {
    @Override
    protected void configure(MapperFactory factory) {
    factory.registerMapper(new CustomMapper<A, Collection<B>>() {
        @Override
        public void mapAtoB(A a, Collection<B> b, MappingContext context) {                     b.addAll(mapperFacade.mapAsList(a.collection, B.class));

            for(B item : b) {
                item.propertyA = a.propertyA;
            }
        }               
    });             
    factory.registerConcreteType(Collection.class, ArrayList.class);
        }           
};  
final Type<Collection<B>> collectionOfB = new TypeBuilder<Collection<B>>() {}.build();
Collection<B> dest = mapper.map(source, TypeFactory.valueOf(A.class), collectionOfB);           
like image 99
Sidi Avatar answered Nov 06 '22 01:11

Sidi