Dozer: Map single field into a List

user424174 picture user424174 · Jun 29, 2012 · Viewed 11.6k times · Source

How do you map a single field into a List / Collection in Dozer?

class SrcFoo {
    private String id;
    private List<SrcBar> bars;
}

class SrcBar {
    private String name;
}

Here are my destination objects:

class DestFoo {
    private List<DestBar> destBars;
}

class DestBar {
    private String fooId; // Populated by SrcFoo.id
    private String barName;
}

I want all DestBar.fooId (entire list of DestBars) to be populated with SrcFoo.id

This question is similar to this one posted here, expect I want to map my single field to every item in the list. Dozer: map single field to Set

I tried the following, but it only populated DestBar.fooId for the first item in the list.

<mapping> 
     <class-a>SrcFoo</class-a> 
     <class-b>DestFoo</class-b> 
     <field>
         <a>bars</a>
         <b>destBars</b>
     </field> 
     <field>
         <a>id</a>
         <b>destBars.fooId</b> <!-- same affect as destBars[0].fooId ? -->
     </field> 
</mapping>

Answer

davidmontoyago picture davidmontoyago · Aug 6, 2012

Dozer does not support that type of mapping. In order to do that type of mapping, you would have to know the indexes on your Collection (static mapping). This a Job for a custom converter, Create a converter of String to List (of DestBar) like this:

public class YourConverter extends DozerConverter<String, List>

Implement the mapping logic in your converter (Just set the String Id where required) and configure your dozer file like this:

<mapping> 
     <class-a>SrcFoo</class-a> 
     <class-b>DestFoo</class-b> 
     ...
     <field custom-converter="yourpackage.YourConverter">
         <a>id</a>
         <b>destBars</b>
     </field> 
</mapping>