javamappingorika

Orika: map constant default value to a field


Is there a way using Orika to set the value of a field to a literal or constant value?

I mean something like:

public class ObjectMapper extends ConfigurableMapper {

        protected void configure(MapperFactory factory) {
             factory.classMap(SourceClass.class, DestinationClass.class)
             .field("myField", "CONSTANT_VALUE")
             .byDefault()
             .register();
        }
}

I can't find something similar in documentation...


Solution

  • According to this section of Orika docs, the only way to set a literal value is by customizing mapping. For example:

    public class ObjectMapper extends ConfigurableMapper {
    
            protected void configure(MapperFactory factory) {
                 factory.classMap(SourceClass.class, DestinationClass.class)
                 .byDefault()
                 .customize(new CustomMapper<SourceClass, DestinationClass>() {
                    @Override
                    public void mapAtoB(SourceClass a, DestinationClass b, MappingContext context) {
                        b.setMyField("CONSTANT_VALUE");
                    }
    
                    // ...
                })
                .register();
            }
    }