Dozer, how to map from java.util.Map to complex type?

对着背影说爱祢 提交于 2019-12-14 01:22:33

问题


I'd like to map from a java.util.Map to a complex type, let's call it 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>

With that I get this error (which is comprehensible): org.dozer.MappingException: No read or write method found for field (Name) in class (interface java.util.Map)

Ok, how do I map from a java.util.Map that has an entry with the key 'Name'? Do I have to create a wrapper object that holds that java.util.Map and provide getters/setters for each entry in that map that I want to map?


回答1:


You can find details for mapping a Map in the Dozer documentation. You need to provide a key not a plain field. Here is an example:

Class 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 file:

<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>

Test code:

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);


来源:https://stackoverflow.com/questions/13395865/dozer-how-to-map-from-java-util-map-to-complex-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!