java Orika - 将对象映射到列表(一对多映射)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15368825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Orika - mapping object to list (one to many mapping)
提问by lbednaszynski
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)?
是否可以将 A 映射到 B 的集合(A.collection.field 应该映射到 B.field 的集合)?
I tried to use custom converter but I have only to manage java.lang.VerifyError:
我尝试使用自定义转换器,但我只需要管理 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)
采纳答案by Sidi
Of course you can map it, you have to just make InnerA public:
当然你可以映射它,你只需要公开 InnerA :
List<B> dest = mapper.mapAsList(sourceA.getCollection(), B.class);
If InnerA is not public, it can not be used by Orika
如果 InnerA 不公开,则 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);