Christian
Christian

Reputation: 23

How to map an object tree using ModelMapper

I'm trying to map an object tree using ModelMapper.

I created an example to illustrate my question:

Code:

@Test
public class TestCase {

  ModelMapper modelMapper = new ModelMapper();

  class Source {
    String value1 = "1.0";
    Sub sub = new Sub();
  }

  class Sub {
    String sub1 = "2.0";
    String sub2 = "3";
  }

  class Destination {
    float numberOne;
    double numberTwo;
    int numberThree;
  }

  TestCase() {
    modelMapper.addMappings(new PropertyMap<Sub, Destination>() {
        @Override
        protected void configure() {
            map(source.sub1, destination.numberTwo);
            map(source.sub2, destination.numberThree);
        }
    });
    modelMapper.addMappings(new PropertyMap<Source, Destination>() {
        @Override
        protected void configure() {
            map(source.value1, destination.numberOne);
            // map(source.sub, destination); // this causes an exception
        }
    });
  }

  public void mapSub() { // works
    Destination destination = new Destination();
    modelMapper.map(new Sub(), destination);
    assertEquals(destination.numberTwo, 2d);
    assertEquals(destination.numberThree, 3);
  }

  public void mapSource() { // how to make this work?
    Destination destination = new Destination();
    modelMapper.map(new Source(), destination);
    assertEquals(destination.numberOne, 1f);
    assertEquals(destination.numberTwo, 2d);
    assertEquals(destination.numberThree, 3);
  }
}

I'm looking for a way to configure a single ModelMapper instance so that the following constraints are satisfied:

  1. modelMapper is able to convert objects of type Sub to Destination
  2. modelMapper is able to convert objects of type Source to Destination
  3. the mapping of the properties in Sub is declared only once

Unfortunately, the line map(source.sub, destination); seems not not work as desired.

My real world scenario contains a bigger object tree with more properties and type conversion. That's the reason why I try to avoid redundant mapping information.

Is it possible to satisfy the constraints?

Upvotes: 1

Views: 3289

Answers (1)

Chun Han Hsiao
Chun Han Hsiao

Reputation: 381

We are working on this for supporting this by introducing a new API.

typeMap.include(Source::getSub, Sub.class)

This new API will be included in next release. Bad new is that you need a getter of this field.

Please refer the issue #354 and the pull request #358 on github for more detail.

Upvotes: 1

Related Questions