我正在使用Dozer将对象A映射到B
Class A {
int indicatorA;
List<A> listA;
// get set methods...
}
Class B{
int indicatorB;
List<B> listB;
// get set methods...
}
我想将A映射到B,我想将parent indicatorA值设置为listB中的所有子节点 示例:
A parentA = new A(); // with indicatorA = 10
A child1A = new A(); // indicatorA value has not set
A child2A = new A(); // indicatorA value has not set
parentA.getListA.add(child1A);
parentA.getListA.add(child2A);
映射后,我希望看到像这样的对象B
B parentB //指标B = 10 和parentB.listB,包含2个对象child1B和chld2B,其中indicatorB值设置为10
如何编写自定义转换器或任何简单的方法来执行此操作? 任何帮助是极大的赞赏.. 感谢
答案 0 :(得分:0)
是的,您需要一个CustomConverter实现,因为无法通过直接映射在List的元素内设置值。
Dozer XML需要一个简单的配置标记,引用CustomConverter类:
<?xml version="1.0" encoding="UTF-8"?>
<mappings xmlns="http://dozer.sourceforge.net"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://dozer.sourceforge.net
http://dozer.sourceforge.net/schema/beanmapping.xsd">
<configuration>
<custom-converters>
<converter type="somepackage.MyConverter" >
<class-a>somepackage.A</class-a>
<class-b>somepackage.B</class-b>
</converter>
</custom-converters>
</configuration>
</mappings>
这是CustomConverter:
public class MyConverter implements CustomConverter {
public Object convert(Object destination, Object source, Class destClass, Class sourceClass){
if (source == null) {
return null;
}
B dest = null;
if (source instanceof A) {
// check to see if the object already exists
if (destination == null) {
dest = new B();
} else {
dest = (B) destination;
}
//dest is your parentB instance
//setting indicatorB value in parentB
dest.setIndicatorB(((A) source).getIndicatorA());
//creating child instances of B
B child1B = new B();
B child2B = new B();
//setting indicatorB values to the child instances as well
child1B.setIndicatorB(((A) source).getIndicatorA());
child2B.setIndicatorB(((A) source).getIndicatorA());
//adding child Bs to parentB list
List<B> listOfBs = new ArrayList<B>();
listOfBs.add(child1B);
listOfBs.add(child2B);
dest.setListB(listOfBs);
return dest;
}
return null;
}
}
如果仅在运行时知道childA的数量,您可以使用CustomConverter中的循环来创建相应数量的childB。