Search code examples
javaorika

Add external data to Orika MappingContext while mapping


I want to add some external properties (something not in the object I'm mapping) to the MappingContext.

Here what I want to accomplish:

    MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
    mapperFactory.classMap(ObjA.class, ObjB.class).customize(new CustomMapper<ObjA, ObjB>() {
        @Override
        public void mapAtoB(ObjA objA, ObjB objB, MappingContext context) {
            objB.setName((String) context.getProperty("name"));
        }
    }).byDefault().register();
    MapperFacade mapper = mapperFactory.getMapperFacade();

    ObjA objA = new ObjA();
    ObjB objB = new ObjB();

    MappingContext context = new MappingContext(); //PROBLEME IS HERE: MappingContext is a abstract class
    context.setProperty("name", "Some information not in objA nor in objB");
    mapper.map(objA, objB, context);

How can I do that? Can I dynamically add data to the context? Or is it an other way to pass additional data to mapper?


Solution

  • The solution is simple:

    MappingContext context = new MappingContext.Factory().getContext();
    context.setProperty("name", "value");
    mapper.map(objA, objB, context);