Dozer更加灵活给对象赋值,对象间拷贝

项目中,经常会遇到各层对象之间相互进行值传递的过程,如在数据据持久层有一持久类ClassA,在视图层可能会变为ViewA,通常情况下,如果两个类结构一样,最常使用的是BeanUtils.copyProperties(src,aim)方法将一个对象的值赋给另一个对象!但是如果属性不同或者名称不同,则需要Dozer来完成,通过灵活的配置,达到不同对象间的拷贝!

如下:
一个XML配置文件:dozerBeanMapping.xml

 


    
	
		false
		MM/dd/yyyy HH:mm
		true
	
	
		com.njusc.view.BoxView
		com.njusc.view.DepView
		
			boxId
			depId
		
		
			depName
			depName
		
	



下面两个简单的类

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。

dozer-5.0.jar (155.1 KB)包下载地址:http://dl.javaeye.com/topics/download/320009d9-b368-3f77-aaf0-7cc8e4c0fadd

 

你可能感兴趣的:(常用的Util__java)