Search code examples
dozer

Dozer - map class field to a flat representation


I've been googling and trying different dozer configuration options but so far couldn't find a simple solution... Problem is as follow:

class A {
 String test;
 B test2;
}
class B {
 String test3;
 String test4;
}

class C {
 String test;
 String test3;
 String test4;
}

Now I would like to map all of the fields from A (including B) to a flat representation in C. Is it possible to map it using just configuration? The problem is that I need to map B in many different classes and I don't want to write a mapping like this for each of them:

<mapping>
    <class-a>A</class-a>
    <class-b>C</class-b>
    <field>
        <a>test2.test3</a>
        <b>test3</b>
    </field>
    <field>
        <a>test2.test4</a>
        <b>test4</b>
    </field>
</mapping>

Would appreciate a solution for that :)


Solution

  • The trick is to use mapping IDs and "this". You need to define caseB only once and can reuse it.

    <mapping map-id="caseB">
        <class-a>B</class-a>
        <class-b>C</class-b>
        <field>
            <a>test3</a>
            <b>test3</b>
        </field>
        <field>
            <a>test4</a>
            <b>test4</b>
        </field>
    </mapping>
    <mapping>
        <class-a>A</class-a>
        <class-b>C</class-b>
        <field map-id="caseB">
            <a>test2</a>
            <b>this</b>
        </field>
    </mapping>