2

在网络上,我发现了许多示例,其中使用 Orika 映射框架将来自一个源对象的字段映射到如下目标对象。

mapperFactory.classMap(BasicPerson.class, BasicPersonDto.class)
            .field("name", "fullName")
            .field("age", "currentAge")
            .register();

但我的要求与这种传统的映射不同。我得到两个源对象和一个目标对象。我需要将第一个源对象的一些字段和第二个源对象的一些字段映射到目标对象。

请发布您对此方案的建议。

4

1 回答 1

5

BoundMapperFacade一个map(A source, B target)方法可以让你映射source到现有的target. 这样您就可以从两个不同的源对象映射到同一个目标对象。

示例代码:

class SourceA {
    String fieldASource;
}

class SourceB {
    String fieldBSource;
}

class Target {
    String fieldATarget;
    String fieldBTarget;
}

public Target mapToTarget() {
    mapperFactory.classMap(SourceA.class, Target.class).field("fieldASource", "fieldATarget").register();
    mapperFactory.classMap(SourceB.class, Target.class).field("fieldBSource", "fieldBTarget").register();

    Target target = new Target();
    SourceA sourceA = new SourceA();
    SourceB sourceB = new SourceB();

    mapperFactory.getMapperFacade(SourceA.class, Target.class).map(sourceA, target);
    mapperFactory.getMapperFacade(SourceB.class, Target.class).map(sourceB, target);

    return target;
}

target将由对象和对象fieldATarget填充其字段。sourceAfieldBTargetsourceB

于 2016-07-04T14:23:32.340 回答