With dozer is it possible to map several fields to one field?

AnthonyJClink picture AnthonyJClink · Dec 15, 2015 · Viewed 8.2k times · Source

We have some legacy data we are attempting to map... The legacy data has fields for month day year...

Is it possible to convert

MyObject.day
MyObject.year
MyObject.month

to

MyOtherObject.date

I could not find any documentation on this subject. Any would be appreciated.

Answer

Przemek Nowak picture Przemek Nowak · Mar 7, 2017

From my side I would recommend a little different solution if you need mapping two fields to single one and vice versa.

The Dozer has the possibility to user setters/getters as way to make mapping. On the class where you have to do it (where you have two fields and wants to map to single field) use the setters where you could provide single field from different object and on the setter/getter logic assign these two fields.

Example mapping:

<mapping type="bi-directional">
<class-a>ClassWithTwoFields</class-a>
<class-b>ClassWithSingleField</class-b>
<field>
  <a get-method="getHelperField" set-method="setHelperField" >helperField</a>
  <b>helperField</b>
</field>

Example getters/setters:

 public FieldType getHelperField() {
    if (!isNull(field1) && !isNull(field2)) {
        return field1 + field2;
    }
    return null;
}

public void setHelperField(FieldType singleField) {
    if (!isNull(singleField)) {
        this.field1 = singleField.part1();
        this.field2 = singleField.part2();
    }
}

It's quick way to deal with the problem.