Search code examples
javadozer

How to map a simple ArrayList to a VO using Dozer


I'm using Dozer to convert my objects. But I've a problem to map a simple List... I retrieve a ResultSet from Hibernate as an Object List and I want to map it to my complex type object.

So, my source is like :

List < Object > list = new ArrayList< Object > ();
list.add("Name");
list.add("Address");

And my Value Object is :

public class MyClass 
{ 
    public String name; 
    public String address; 
}

I just want to map list[0] ==> MyClass.name and list[1] ==> MyClass.address properties but I don't find how...

Thanks for your help !


Solution

  • For some reason Dozer does Not support this (the ideal situation):

    <mapping>
        <class-a>MyClass</class-a>
        <class-b>java.util.List</class-b>       
        <field>          
            <a is-accessible="true">name</a>
            <b>this[0]</b>
        </field>        
    </mapping>
    

    It would only map to name the whole string representation of the List, so your name property would end up with the value [Name, Address].

    Your best option would be to put your List in a holder class and map it like this:

    <mapping>
        <class-a>MyClass</class-a>
        <class-b>MyHolder</class-b>     
        <field>          
            <a is-accessible="true">name</a>
            <b>holded[0]</b>
        </field>
        <field>          
            <a is-accessible="true">address</a>
            <b>holded[1]</b>
        </field>    
    </mapping>
    

    MyHolder class just contains your List instance in the holded field and provide access to it with a getter method.

    In the field mappings is-accessible="true" is required because MyClass properties are public and have no accessors. I recommend you to make those properties private and create accessor methods.