Orika:将常量默认值映射到字段

时间:2016-10-05 10:09:01

标签: java mapping orika

有没有办法使用Orika将字段值设置为文字或常量值?

我的意思是:

public class ObjectMapper extends ConfigurableMapper {

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

我无法在文档中找到类似内容......

2 个答案:

答案 0 :(得分:1)

根据Orika文档的this section,设置文字值的唯一方法是自定义映射。例如:

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

答案 1 :(得分:1)

我找到了一个简单的解决方案

public class ObjectMapper extends ConfigurableMapper {

    protected void configure(MapperFactory factory) {
         factory.classMap(SourceClass.class, DestinationClass.class)
         .field("", "myField:{|setMyField('MY CONSTANT')}")
         .byDefault()
         .register();
    }
}

源可以是空的,您只需要用属性名称和setter方法填充目标即可。