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>
    
    <configuration>
        <stop-on-errors>falsestop-on-errors>
        <date-format>MM/dd/yyyy HH:mmdate-format>
        <wildcard>truewildcard>
    configuration>
    <mapping>
        <class-a>com.njusc.view.BoxViewclass-a>
        <class-b>com.njusc.view.DepViewclass-b>
        <field>
            <a>boxIda>
            <b>depIdb>
        field>
        <field>
            <a>depNamea>
            <b>depNameb>
        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。

转载于:https://www.cnblogs.com/XL-Liang/archive/2013/03/22/2975105.html

你可能感兴趣的:(Dozer更加灵活给对象赋值,对象间拷贝)