2012-11-15 82 views
2

我想從java.util.Map映射到複雜類型,我們稱之爲Abc。推土機,如何從java.util.Map映射到複雜類型?

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

好的,我該如何映射一個java.util.Map,它有一個鍵入'Name'的條目?我是否必須創建一個包裝對象來保存該java.util.Map,併爲該映射中要映射的每個條目提供getters/setters?

回答

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