Dozer更加灵活给对象赋值,对象间拷贝
项目中,经常会遇到各层对象之间相互进行值传递的过程,如在数据据持久层有一持久类ClassA,在视图层可能会变为ViewA,通常情况下,如果两个类 结构一样,最常使用的是BeanUtils.copyProperties(src,aim)方法将一个对象的值赋给另一个对象!但是如果属性不同或者名 称不同,则需要Dozer来完成,通过灵活的配置,达到不同对象间的拷贝!
如下:
一个XML配置文件:dozerBeanMapping.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mappings PUBLIC "-//DOZER//DTD MAPPINGS//EN" "http://dozer.sourceforge.net/dtd/dozerbeanmapping.dtd"> <mappings> <!-- <class-a>指定所要复制的源对象,<class-b>复制的目标对象,<a>源对象的属性名, <b>目标对象的属性名。 wildcard默认为true,在此时默认对所有属性进行map,如果为false,则只对在xml文件中配置的属性进行map。 --> <configuration> <stop-on-errors>false</stop-on-errors> <date-format>MM/dd/yyyy HH:mm</date-format> <wildcard>true</wildcard> </configuration> <mapping> <class-a>com.njusc.view.BoxView</class-a> <class-b>com.njusc.view.DepView</class-b> <field> <a>boxId</a> <b>depId</b> </field> <field> <a>depName</a> <b>depName</b> </field> </mapping> </mappings>
下面两个简单的类
package com.njusc.view; public class BoxView { private String boxId; private String depName; public String getBoxId() { return boxId; } public void setBoxId(String boxId) { this.boxId = boxId; } public String getDepName() { return depName; } public void setDepName(String depName) { this.depName = depName; } }
package com.njusc.view; public class DepView { private String depId; private String depName; public String getDepId() { return depId; } public void setDepId(String depId) { this.depId = depId; } public String getDepName() { return depName; } public void setDepName(String depName) { this.depName = depName; } }
下面看具体的操作:
package com.njusc.util; import java.util.ArrayList; import java.util.List; import org.dozer.DozerBeanMapper; import com.njusc.view.BoxView; import com.njusc.view.DepView; public class DozerBeanMapperUtil { public static void main(String[] args) { BoxView bv = new BoxView(); bv.setBoxId("1234"); bv.setDepName("测试"); DozerBeanMapper mapper=new DozerBeanMapper(); BoxView newbv = new BoxView(); //mapper.map(bv, newbv); //这种方式或下面的方式都可以 newbv = (BoxView)mapper.map(bv, BoxView.class); System.out.println(newbv.getDepName()+newbv.getBoxId()); DozerBeanMapper mapper1=new DozerBeanMapper(); List myMappingFiles = new ArrayList(); myMappingFiles.add("dozerBeanMapping.xml"); mapper1.setMappingFiles(myMappingFiles); DepView dep = new DepView(); //不同对象间拷贝 mapper1.map(bv, dep); System.out.println(dep.getDepId()+dep.getDepName()); } }
通过mapper.setMappingFiles()设置映射文件,可以添加多个配置文件,也可以把所有的映射写在一个配置文件里面。 更多复杂例子请见它自带的doc。