Dozer,如何从java.util.Map映射到复杂类型?

时间:2012-11-15 10:44:59

标签: getter dozer complextype map

我想从java.util.Map映射到复杂类型,我们称之为Abc。

<mapping>
  <class-a>java.util.Map</class-a>
  <class-b bean-factory="xyz.AbcBeanFactory" factory-bean-id="AbcBeanFactory">
    xyz.Abc
  </class-b>
  <field>
    <a>Name</a>
    <b>companyName</b>
  </field>
</mapping>

有了这个我得到这个错误(这是可以理解的): org.dozer.MappingException:找不到类(接口java.util.Map)中字段(Name)的读取或写入方法

好的,我如何映射来自java.util.Map的条目具有键&#39;名称&#39;?我是否必须创建一个包含java.util.Map的包装器对象,并为该地图中我要映射的每个条目提供getter / setter?

1 个答案:

答案 0 :(得分:4)

您可以找到有关映射地图in the Dozer documentation的详细信息。您需要提供密钥而不是普通字段。这是一个例子:

班级Abc:

package com.test;

public class Abc {
    private String companyName;
    private String companyAddress;

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public String getCompanyAddress() {
        return companyAddress;
    }

    public void setCompanyAddress(String companyAddress) {
        this.companyAddress = companyAddress;
    }
}

映射文件:

<mapping>
    <class-a>java.util.Map</class-a>
    <class-b>com.test.Abc</class-b>
    <field>
        <a key="name">this</a>
        <b>companyName</b>
    </field>
    <field>
        <a key="address">this</a>
        <b>companyAddress</b>
    </field>
</mapping>

测试代码:

Map<String, String> map = new HashMap<String, String>();
map.put("name", "Company Inc.");
map.put("address", "XYZ Commercial Street");

Abc destObject =  dozerMapper.map(map, Abc.class);