Reputation: 23
I'm trying to map an object tree using ModelMapper.
I created an example to illustrate my question:
Sub
contains several properties.Source
contains an object of type Sub
and (at least) another property.Destination
holds a flat list of properties.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:
modelMapper
is able to convert objects of type Sub
to Destination
modelMapper
is able to convert objects of type Source
to Destination
Sub
is declared only onceUnfortunately, 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
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