[java]代码库
package bean_mapping;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.junit.Before;
import org.junit.Test;
public class TestBeanMapping {
MapperFacade mapper = null;
@Before
public void init() {
//创建mapper的工厂类
MapperFactory factory = new DefaultMapperFactory.Builder().build();
//注册一个mapper,这段可以同过继承configurableMapper类,配置成spring bean
factory.registerClassMap(factory.classMap(SourceObj.class, DescObj.class)
//设置正向空值不复制,反向空值不复制
.mapNulls(false).mapNullsInReverse(false)
//相同的字段不需要显示声明
//.field("prop1", "prop1")
.field("intProp2", "prop2")
//List, Array, Map类型的复制方式
.field("listProp3{}", "prop3{}").mapNulls(true)
.byDefault().toClassMap());
//获取mapper
mapper = factory.getMapperFacade();
}
@Test
public void testMapping() {
//构建源对象
SourceObj source = new SourceObj();
source.setProp1("test");
source.setIntProp2("test2");
List<String> propList = new ArrayList<String>();
propList.add("TestString");
propList.add("TestString2");
source.setListProp3(propList);
//转换成目标对象
DescObj desc = mapper.map(source, DescObj.class);
assertEquals(source.getProp1(), desc.getProp1());
assertEquals(source.getIntProp2(), desc.getProp2());
assertEquals(desc.getProp2(), "test2");
assertEquals(desc.getProp3().size(),2);
}
}
[源代码打包下载]
中级程序员
by: 路易斯陈凯瑞 发表于:2014-06-20 10:58:59 顶(0) | 踩(0) 回复
需要用到的jar包
orika-core-1.4.0
paranamer.jar
javassist-GA.jar
回复评论