简体   繁体   中英

Is it possible to map fields from two source objects to a target object using Orika Mapper?

On the web I found many example where fields from one source object are being mapped to a target object like below using Orika Mapping framework.

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

But my requirement is different from this traditional mapping. I am getting two source objects and one target object. I need to map some of the fields from first source object and some of the fields from second source object to the target object.

Please post your suggestions for this scenario.

The BoundMapperFacade has a map(A source, B target) method which allows you to map from source to an existing instance of target . That way you can map from two different source object onto the same target object.

Sample code:

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;
}

The target will have its fieldATarget field filled from the sourceA object and fieldBTarget from the sourceB object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM